finding a preorder of some digits with their levels in BST

眉间皱痕 提交于 2019-12-13 03:30:35

问题


I have a list that has e.g. 5 digits which each digit has its own level in BST :

list-->

[digit :6  level:1, digit :3  level:2, digit :5   level:3, digit :2 level:3, digit:1   level:4]

how can I find its preorder which is { 6,3,2,1,5} ?

Consider that I have 10000 digits in my list above.

thanks


回答1:


To traverse a BST in preorder you have to 1. Visit the root (i.e. your number) 2. Traverse the left subtree. 3. Traverse the right subtree.

Each subtree is recursively traversed in the same way (root, left and right).

In your example you don't have a clear indication of which number is to the left or right of which. Once you get to your 10000 digits of your list, you will have many numbers at the same level (say level 20) and unless your list is structured in a better way that represents the BST you wont manage.

Just by saying digit: 65 is at level:20, you have no indication whether it is to the left of digit:70 at level:19 or to the right of digit: 60 at level: 19.

UPDATE (as indicated by Anil):

The position of each node in the tree can be determined by analysing the two levels above it. As described by Anil, the lowest common ancestor will determine whether a number A at level X should be to the left of number B or number C at Level X-1, depending on whether their common parent node at level X-2 is smaller or greater than A.

Given that pre-order is depth-first you'll have to iterate (or recursively process) through the list multiple times i'm afraid. If you don't have any limitations of memory you could build the tree first.



来源:https://stackoverflow.com/questions/4539698/finding-a-preorder-of-some-digits-with-their-levels-in-bst

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