BST from Preorder by just inserting the nodes in same order

拜拜、爱过 提交于 2019-12-05 06:29:18

问题


To construct a BST from the preorder traversal given, if I try to insert in the BST in the same order as given in preorder, I get the BST. So, we don't to create the in-order by sorting of the elements or perform any other alogrithm?

Is there an example which shows that tree can't be constructed by just inserting the elements ?


回答1:


You're correct... you can just insert the nodes in the order given by a preorder traversal to rebuild the tree.

The first node inserted must be placed at the right place, since it's the root and a preorder traversal always places the root first. What follows in the preorder traversal is the preorder layout of the left subtree followed by the right subtree. As the left subtree nodes are inserted, they are inserted by going left from the root, then recursively applying the same procedure on that subtree. The right subtree is rebuilt the same way. Using induction, you can formally prove this if you like.

Hope this helps!



来源:https://stackoverflow.com/questions/19640382/bst-from-preorder-by-just-inserting-the-nodes-in-same-order

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