Download presentation
Presentation is loading. Please wait.
Published byInge Atmadja Modified over 5 years ago
1
Trees are Everywhere family genealogy organizational charts
corporate government military folders/files on a computer compilers: parse tree a = (b + c) * d; = a * + d b c Oct 19, 2001 CSE 373, Autumn 2001
2
First child/next sibling
struct TreeNode { Object element; TreeNode *firstChild; TreeNode *nextSibling; } C:\ MyMail cse373 D101 school pers hw1 hw2 proj1 coll.h coll.cpp poly.h Oct 19, 2001 CSE 373, Autumn 2001
3
Tree traversal preorder/postorder traversal
TreeNode::printTree(TreeNode tnode) { tnode.print(); for each child c of tnode c.printTree(); } preorder/postorder traversal int TreeNode::numNodes(TreeNode tnode) if (tnode == NULL) return 0; else sum = 0; sum += numNodes(c); return 1 + sum; Oct 19, 2001 CSE 373, Autumn 2001
4
Binary trees A binary tree is a tree where all nodes have at most two children. struct BinaryNode { Object element; BinaryNode *left; BinaryNode *right; } 1 2 1 3 2 3 4 4 5 6 7 5 6 7 Oct 19, 2001 CSE 373, Autumn 2001
5
Binary Search Trees Associated with each node is a key value that can be compared. Binary search tree property: every node in the left subtree has key whose value is less than the value of the root’s key value, and every node in the right subtree has key whose value is greater than the value of the root’s key value. Oct 19, 2001 CSE 373, Autumn 2001
6
Example 5 4 8 1 7 11 3 BINARY SEARCH TREE Oct 19, 2001
CSE 373, Autumn 2001
7
Counterexample 8 5 11 2 7 6 10 18 4 15 20 NOT A BINARY SEARCH TREE 21
Oct 19, 2001 CSE 373, Autumn 2001
8
find Basic idea: compare the value to be found to the key of the root of the tree. If they are equal, we are done. If they are not equal, recurse depending on which half of the tree the value to be found should be in if it is there. BST::find(const int x, BNode<int> *t) { if (t == NULL) return NULL; else if (x < t->element) return find(x, t->left); else if (x > t->element) return find(x, t->right); else return t; // match } Oct 19, 2001 CSE 373, Autumn 2001
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.