Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than.

Similar presentations


Presentation on theme: "Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than."— Presentation transcript:

1 Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

2 Binary Search Tree void insert (struct node *root, struct node *entry) { /* where to insert is really algorithm dependent. A generic case only: entry is to replace the left node of root */ if (head->left) { entry->left = head->left->left; entry->right = head->left->right; } head->left = entry; }; void delete (struct node *root, struct node *entry) { /* The key is to find a node that has an entry as a child */ // Three Cases: 1) Leaf node 2) A node with one child: remove the node and replace it with its child 3) A node with two children: Replace the value of entry with the largest value in the left, or the smallest value in the right, and delete the node with largest value in the left or the smallest value in the right. }; struct node * search (struct node *root, int val)//DFS { struct node * tmp = NULL; if (!root) return NULL; else if (root->data != val) tmp = search(root->left, val); if (!tmp) tmp = search(root->right, val); return tmp; } int main() { struct node num[10] = { … }; struct node root = {0, NULL, NULL}; for (int i=0; i<10; i++) { insert (&root, &num[i]); } … return 0; }

3 Breadth/Depth-first Traversal BFS: 1) A->B->C->D->E->F->G->H 2)A queue is needed to keep the nodes while the tree is being traversed DFS: 1)A->B->D->C->E->F->H->G 2)Usually a recursive function A BC DEFG H root

4 Weeks 8-9 IO Standard IO (stdin, stdout) and Pipes Formatted IO File IO System Calls System interface to obtain services from the OS, include many subsystems Memory Scheduler File/Storage System Inter-process Communication and Network, etc A popular subsystem: File system File descriptors Low level IO File Management Examples

5 Programs and Standard I/O Program Standard Input (STDIN) Keyboard Output from another program A file Standard Output (STDOUT) Screen Input to another program A file Standard Error (STDERR) stdin, stdout cmd < inputfile cmd > outputfile Numbered file descriptors 0: stdin: used by function scanf() 1: stdout: used by function printf() 2: stderr …

6 Pipes and Input/Output Redirection When a file descriptor is assigned to something other than a terminal, it is called I/O redirection A file (the contents of the file are fed to a program as if you typed it): wc < text_file A pipe (the output of another program is fed as input as if you typed it) The shell can attach things other than your screen to standard output. A file (the output of a program is stored in file): ls > lsout (>> for append) A pipe (the output of a program is fed as input to another program) Pipes cmd1 | cmd2 | cmd3 IO Redirection cmd1 outputfile: specifies the input and output file cmd1 | cmd2 2>&1 | cmd3 : redirect stderr(:2) to stdout and input it to cmd3

7 Pipes A pipe is a holder for a stream of data. A pipe can be used to hold the output of one program and feed it to the input of another. Separate 2 commands with the “|” character. prog1 prog2 STDOUT STDIN

8 Redirection/Pipe Examples wc < test1 ls > lsout ls >> lsout ls | wc

9 Formatted IO Output: printf Input: scanf Arguments: a format string, followed by the arguments printf (char *fmt, arg1, arg2, …) scanf (char *fmt, arg1, arg2, …) Arguments for scanf have to be the memory addresses

10 Formatting Output goes to stdout Input comes from stdin Format String: regular string + conversion specification Start of a format specification: % Width, precision, adjustment: Between ‘%’ and the conversion character, in order i) ’-’: specifies left adjustment of the converted argument. A number: the minimum field width.  ii) ‘.’: separates the field width from the precision: A number: precision. string(max num of characters); floating(num of digits after the decimal point); integer(min num of digits)  iii) l or h: long or short.  Example : Hello, World (12 characters) printf(“%s”, s); %-15s; %.10s; % -15.10s; %15.10s; Refer to Chapter 7.2 Formatted Output  Go to web page http://www.cplusplus.com/reference/clibrary/cstdio/printf/ for more detailshttp://www.cplusplus.com/reference/clibrary/cstdio/printf/

11 String-based input/output String-based input int sscanf (char *str, char *fmt, arg1, arg2, …); String-based output int sprintf (char * str, const char * format,... ); Example: char st[]=“3.21, 4.33”; float x,y; sscanf(st,”%f,%f”,&x,&y);//result: x=3.21, y=4.33 char newst[32]; sprintf(newst,”%f, %f”, y, x);//result: newst=“4.33,3.21”

12 Variable length arguments A function may be called with a varying number of arguments of varying types #include, a new datatype: va_list //declare a variable: va_list ap Associated macro functions: va_start(ap, last) Initialize ap to be the va_list after the argument: last. This need to be done before va_arg and va_end va_arg(ap, int) Expand ap to an expression that has type/value that match int ap moves to the next argument in the variable list va_end(ap) Cleanup the variable argument list when done

13 Variable length arguments #include int add(int n,...); int main() { printf("%d\n", add(4,1,2,3,4)); printf("%d\n", add(3,1,2,3,)); return 0; } int add(int n,...) { int i, sum, tmp; va_list arg; va_start(arg, n); for(sum = i = 0; i < n; ++i){ tmp = va_arg(arg, int); sum += tmp; } va_end(arg); return sum; }

14 Variable length arguments void foo(char *fmt,...) { va_list ap; int d; char c, *p, *s; va_start(ap, fmt); while (*fmt) switch(*fmt++) { case 's': /* string */ s = va_arg(ap, char *); printf("string %s\n", s); break; case 'd': /* int */ d = va_arg(ap, int); printf("int %d\n", d); break; case 'c': /* char */ c = va_arg(ap, char); printf("char %c\n", c); break; } va_end(ap); }

15 File Accesses Files and file descriptors: FILE *fp; FILE *fopen(char *name, char *mode); Name can be a long path Mode: a combination of ‘r’, ‘w’, ‘x’, or ‘a’ File input/output int getc(FILE *fp) int putc(int c, FILE *fp); These works with default stdin/stdout: getchar() putchar() include “stdio.h” int main() { FILE *fp=fopen(“test.txt”,”r”); int c; int n=0; while((c=getc(fp))!=EOF) { if(c==‘$’) n++; } printf(“file contains %d $\n”,n); fclose(fp); }

16 File Accesses “r“: Open a file for reading. The file must exist. "w“: Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a“: Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. "r+“: Open a file for update both reading and writing. The file must exist. "w+“: Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a+“: Open a file for reading and appending.

17 Line-oriented input/output int getline(char *line, size_t n, FILE *fp) char *fgets(char *line, size_t n, FILE *fp); gets(char *line, size_t n); /* buggy, never use it */ char *fputs(char *line, FILE *fp); Don’t use scanf() before fgets().

18 Error handling fprintf(stderr, char *fmt, arg1, arg2, …) exit(1): exit with non-zero status ferror(FILE *fp): test for any error on fp feof(FILE *fp) : test for end-of-file perror(char *s): print the error message, s, to stderr for the last system or library calls


Download ppt "Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than."

Similar presentations


Ads by Google