Determine if two binary trees are equal

前端 未结 7 2015
臣服心动
臣服心动 2020-12-04 22:33

What would be the efficient algorithm to find if two given binary trees are equal - in structure and content?

7条回答
  •  旧时难觅i
    2020-12-04 23:14

    Since it's a proven fact that - it is possible to recreate a binary tree as long as we have the following:

    1. The sequence of nodes that are encountered in an In-Order Traversal.
    2. The sequence of nodes that are encountered in a Pre-Order OR Post-Order Traversal

    If two binary trees have the same in-order and [pre-order OR post-order] sequence, then they should be equal both structurally and in terms of values.

    Each traversal is an O(n) operation. The traversals are done 4 times in total and the results from the same-type of traversal is compared. O(n) * 4 + 2 => O(n) Hence, the total order of time-complexity would be O(n)

提交回复
热议问题