Binary Tree A Tree Binary Trees The Binary tree means that the node can have maximum two children. Here, binary name itself suggests that 'two'; therefore, each node can have either 0, 1 or 2 children. Example of Binary Tree Binary Search Tree A binary tree which has the following properties: -The left subtree of a node contains only nodes with keys less than the node's key. -The right subtree of a node contains only nodes with keys greater than or equal to the node's key. -Both the left and right subtrees must also be binary search trees. Example of Binary Search Tree 20 10 20 15 15 5 30 15 4 5 3 1 14 8 18 13 18 8 25 35 7 15 17 10 24 8 20 11 4 19 18 21 Example of Not Binary Search Tree 2 5 10 25 22 35 25 39 15 20 51 34 13 33 Answer: 20 10 5 25 2 33 25 22 15 39 13 35 34 51 Tree Traversal Tree traversal also known as tree search and walking the tree is a form of graph traversal and refers to the process of visiting retrieving, updating, or deleting each node in a tree data structure, exactly once. Tree Traversal Strategies • Breadth First Starting at either the highest or lowest node and visiting each level until the other end is reached. -Lowest to Highest -Highest to Lowest • Depth First Proceeding as far as possible to the right (or left), and then returning one level, stepping over and stepping down. Left to Right Right to Left Breadth First Traversal Traverse through one level of children nodes, then traverse the level of grandchildren's nodes. Consider Top Down, left to right traversal. Example: Level 0 A B D Level 1 C E F G Level order : A, B, C, D, E, F, G Level 2 Depth First Traversal Traverse through left subtrees first, then traverse through the right subtrees. V = visiting a node L = traversing the left subtree R = traversing the right subtree Options -VLR (Pre Order Tree Traversal) -LVR (In order Tree Traversal) -LRV (Post order Tree Traversal) Example Depth First Traversal START Level 0 1 2 4 8 VLR PRE-ORDER: Level 1 3 5 9 1, 2, 4, 8, 9, 5, 3, 6, 7, 10 LRV POST-ORDER: 8, 9, 4, 5, 2, 6, 10, 7, 3, 1 6 7 10 Level 2 Level 3 LVR IN-ORDER: 8, 4, 9, 2, 5, 1, 6, 3, 10, 7 LEVEL-ORDER: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Code for Depth First Traversal 45 10 7 90 12