Reconstructing binary tree from inorder and preorder traversals

江枫思渺然 提交于 2019-12-04 14:36:28
in = {1,3,2,5}; pre = {2,1,5,3};

I've some difficulties constructing the tree 'by hand'. pre shows that 2 must be the root, in shows that {1,3} are nodes of the left subtree, {5} is the right subtree:

      2
     / \
    /   \
  {1,3} {5}

But knowing this, 3 can't be the last element in pre because it is clearly an element of the left subtree and we have a right subtree. Valid preorder traversals for these trees are {2,1,3,5} or {2,3,1,5}. But {2,1,5,3} is impossible.

Maybe the bug is not in this method but in your algorithm to create inorder and preorder traversals. Or, could it be, that you chose the values for in[] and pre[] randomly?

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