1

Is preorder traversal enough to check if a tree is subtree of a binary tree?

Are there any scenarios which I can miss if I use just the preorder traversal?

What other methods can be used to check if a tree is subtree?

Also, what happens if my binary tree contains non-unique values at nodes?

Ryan Cyrus
  • 111
  • 2

2 Answers2

2

Because different trees can have the same pre-order label sequence (easy exercise).

To check equality, recurse on both trees at the same time. That gives you a simple (if not terribly efficient) algorithm for checking whether a tree is a subtree of another one.

Raphael
  • 73,212
  • 30
  • 182
  • 400
0

You can use the following algo to check whether tree SMALL is a part of tree LARGE:

  1. Compute height of smaller tree: small_height = height(SMALL)
  2. Recurse large tree, computing height in each node
  3. If node height is the same as small tree height, compare trees:

recurse(tree) left_height = recurse(tree.left) right_height = recurse(tree.right) height = max(left_height,right_height) + 1 if height==small_height compare_trees(SMALL,tree) return height

Time analysis is simple: you may visit each node in large tree once or twice - once when computing height and another time when comparing it to small tree. So, browsing large tree is O(n), and computing height of small tree require to visit each node so it's O(m).

Bulat
  • 2,113
  • 1
  • 11
  • 17