Construct binary tree from inorder and level traversal

☆樱花仙子☆ 提交于 2020-01-02 14:48:10

问题


Need help finding a way to construct a binary tree given the inorder and level traversal. Is it possible to do it using recursion since the level traversal has to be done by using a queue?


回答1:


Here's how you can approach this problem. It's easier to think of how to approach each step by looking from reverse:

      8
     / \
    4   9
   / \   \
  2   6   10
 /
1

You have the following:

Inorder: 1 2 4 6 8 9 10

Level: 8 4 9 2 6 10 1

Level 1 - Root

A level traversal is a left to right, top to down traversal of the tree (like breadth-first search). In this example, you know that 8 will be the root node. Now looking at the inorder traversal, we know that 1 2 4 6 make up the left subtree and 9 10 make the right subtree. So we have:

        8
1 2 4 6   9 10

While preserving order, create a copy of the level traversal without the nodes we are going to visit for the left and right recursive construction. Below notes will go through the left tree steps and what is passed through:

Level 2 - Left Subtree

Inorder: 1 2 4 6

Level: 4 2 6 1

  • Root: 4
  • Left subtree: 1 2
  • Right subtree: 6

Result:

        8
       /  9 10
      4
  2 1  \
        6

Level 3 - Left Subtree

Inorder: 1 2

Level: 2 1

  • Root: 2
  • Left subtree: 1
  • Right subtree: empty

Result:

       8
      /  9 10
     4
    / \   
   2   6
  /
 1

Now that we're done recursing all the way left, hopefully you can walk through on how to deal with the right children of the tree! Once you have the algorithm, you should be able to construct back the tree given two different traversals. The key is to recognize based on the two traversals how to determine the root at each recursive call, and the rest should follow through.



来源:https://stackoverflow.com/questions/15399835/construct-binary-tree-from-inorder-and-level-traversal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!