17.3. Binary Trees Part 1¶
17.3.1. Binary Trees Part 1¶
17.3.1.1. Binary Trees¶
A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees, called the left and right subtrees, which are disjoint from each other and from the root.
Notation: Node, children, edge, parent, ancestor, descendant, path, depth, height, level, leaf node, internal node, subtree.
ABCDEFGHI
17.3.1.2. A Recursive Data Structure¶
2383510A node followed by a list2051030154025Left sub-tree is a binary treeRight sub-tree is a binary tree
17.3.1.3. Binary Tree Node Class¶
17.3.1.4. Question¶
Write a recursive function named count that, given the root to a binary tree, returns a count of the number of nodes in the tree. Function count should have the following prototype:
int count(BinNode root)
17.3.1.5. Traversals¶
Any process for visiting the nodes in some order is called a traversal.
Any traversal that lists every node in the tree exactly once is called an enumeration of the tree’s nodes.
Preorder traversal: Visit each node before visiting its children.
Postorder traversal: Visit each node after visiting its children.
Inorder traversal: Visit the left subtree, then the node, then the right subtree.
17.3.1.6. Preorder Traversal (1)¶
17.3.1.7. Preorder Traversal (2)¶
17.3.1.8. How not to write a traversal¶
Problems:This has a major bugIt puts the focus in the wrong place: Should focus on the current node, not the children. This version is therefore more complicated.