algoritmauzmanı
Sign in
TREN
6.3Binary Tree with Linked Nodes
Lesson 6.3.7

Search, node count and height

Most tree questions are solved with the same pattern: "the answer comes from the answer for the left subtree and the answer for the right subtree". In this lesson you write three functions with this pattern: searching for a value, counting the nodes and finding the of the tree. All three are a few lines long and work in the spirit of postorder.

What you will learn
  • Why a search in an unordered binary tree has to look at both subtrees
  • How the node count and the height are built from the subtrees' answers
  • Why the height of an empty tree is -1
6 minTime O(n)Memory O(h)C · Java · Python
Know these first:6.3.5 Postorder traversal

1Idea

Search

In this tree values are not placed in any order, so you cannot tell which side the value is on. search first looks at the node itself; if that is not it, it searches the left subtree, and if the value is not there either, it moves to the right subtree. It returns the address of the node it finds, or NULL if the value is not in the tree. In the worst case every node is checked. In a binary search tree only one side is taken at each step.

Node count

An empty tree has no nodes: 0. In a non-empty tree the node count is the root itself (1) plus the nodes in the left subtree and in the right subtree. On the sample tree that is 1 + 3 + 2 = 6. In an array tree this number is already in the count field; linked nodes do not keep it, so it has to be counted.

Height

The is the number of edges on the path from the root to the farthest leaf. A node's height is one more than the larger of its children's heights. A single node has two empty children; for its height to come out as 0, the height of an empty tree is taken to be -1. The sample tree has height 2: two edges from 10 down to 40.

Some books and exams measure height in levels, not edges; then a single node has height 1, an empty tree 0, and the code starts with return 0. Check which definition the question uses.

2Step by step

The drawing works out the height of the sample tree. The calls go down to the leaves first; a node's height is found once both of its children have answered, and it is written under the node. Calls on NULL return -1 and are not shown.

100x2a0200x2c8300x2f0400x318500x340600x368
Call stack
  1. Start. height(root) is called; 10, then 20, wait for their children to answer.
  2. Both children of 40 are NULL and both return -1. The height of 40 is 1 + max(-1, -1) = 0.
  3. 50 is a leaf too: height 0.
  4. Both answers for 20 are in: 0 and 0. The height of 20 is 1 + 0 = 1.
  5. Now the right side of 10. 60 is a leaf: 0.
  6. The left of 30 gives 0, its right is NULL, so -1. The height of 30 is 1 + max(0, -1) = 1.
  7. Both answers for the root are 1. The height of 10 is 1 + 1 = 2.
  8. The height of the tree is the root's: 2. Every node was visited once.

struct TreeNode {    int data;    struct TreeNode* left;    struct TreeNode* right;}; struct TreeNode* search(struct TreeNode* root, int value) {    if (root == NULL) return NULL;            // not found    if (root->data == value) return root;    struct TreeNode* found = search(root->left, value);    if (found != NULL) return found;          // found on the left    return search(root->right, value);} int countNodes(struct TreeNode* root) {    if (root == NULL) return 0;    return 1 + countNodes(root->left) + countNodes(root->right);} int height(struct TreeNode* root) {    if (root == NULL) return -1;              // empty tree    int lh = height(root->left);    int rh = height(root->right);    return 1 + (lh > rh ? lh : rh);}
class TreeNode {    int data;    TreeNode left, right;    TreeNode(int data) { this.data = data; }} TreeNode search(TreeNode root, int value) {    if (root == null) return null;            // not found    if (root.data == value) return root;    TreeNode found = search(root.left, value);    if (found != null) return found;          // found on the left    return search(root.right, value);} int countNodes(TreeNode root) {    if (root == null) return 0;    return 1 + countNodes(root.left) + countNodes(root.right);} int height(TreeNode root) {    if (root == null) return -1;              // empty tree    int lh = height(root.left);    int rh = height(root.right);    return 1 + Math.max(lh, rh);}
class TreeNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None def search(root, value):    if root is None:             # not found        return None    if root.data == value:        return root    found = search(root.left, value)    if found is not None:        # found on the left        return found    return search(root.right, value) def count_nodes(root):    if root is None:        return 0    return 1 + count_nodes(root.left) + count_nodes(root.right) def height(root):    if root is None:             # empty tree        return -1    lh = height(root.left)    rh = height(root.right)    return 1 + max(lh, rh)

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

In the worst case all three functions visit every node once.

Memory
O(h)

The call stack grows as long as the path from the root to the deepest leaf: the height h of the tree.

A search that finds the value early stops early, but the worst case stays the same: if the value is not in the tree, every node is checked. The node count and the height always walk the whole tree.

4Common mistake

A common mistake in search is returning the right side's result without checking the left side's:

search(root->left, value);           // the result is lostreturn search(root->right, value);

Even if the value is found on the left, nobody uses that result, and the function returns the answer from the right side, which is NULL. In height, a common mistake is returning 0 for an empty tree and reading the result as a count of edges: then every height comes out one too high.

5Try it

What is the height of a tree made of a root and its left child only? (An empty tree is -1.)

Show the answer

The answer is B. The left child is a leaf with height 0. The root's height is 1 + max(0, -1) = 1. There is one edge from the root to the leaf.

In an unordered binary tree with n nodes, how many nodes does a search check in the worst case?

Show the answer

The answer is C. Where a value sits does not follow any order. If the value is not in the tree, or is in the last place checked, every node is looked at.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.