Understanding pseudocode to construct tree from preorder traversal

回眸只為那壹抹淺笑 提交于 2019-12-24 11:04:43

问题


I need to do something similar to the task described in this question:
Construct tree with pre-order traversal given

There is a really helpful answer here, but I don't understand the pseudocode fully, so I was wondering if someone could help describe to me what is going on.

k = 0 // Initialize
input = ... get preorder traversal vector from user ... // Get input
Reconstruct(T) // Reconstruct method with tree input
  if input[k] == N // If element of input is N
    T = new node with label N // Make a new node with label N in tree T
    k = k + 1  // Increment k for next loop (Is this whole thing a loop? or a method call?)
    Reconstruct(T.left) // ?????
    Reconstruct(T.right) // ?????
 else // If element of input is L
    T = new node with label L // Make a new node with label L in tree T
    T.left = T.right = null // ?????
    k = k + 1 // Increment k for next loop

I have written my understanding of things in the comments and I'd really appreciate it if someone could check that my understanding is correct, and what the question mark bits are doing. Also, is this pseudocode making a new tree by running through the input and backtracking whenever an L is encountered in the input? Or is it reconstructing an existing binary tree?


回答1:


There is no loop. k is a globally-scoped variable which can be accessed within Reconstruct(T). It is simply the current index of the character-array (the input string).

As explained in the question you referenced (Contsruct Tree with Pre-Order Traversal), The proper algorithm is to do the left-child of a node, then the right-child Which is what you see in the true section of the if. If the current node happens to be a leaf, L, then do not give it children and return to the calling function.

What this function does is follows the left edge of the tree, adding children to all N nodes and not adding children to all L nodes (aka leaves) until the string finishes.

Edit: When the author of the pseudocode says T.left = T.right = null, it means that at this point, the current node has no left or right child (because it is a leaf). This is just an assertion and does not necessarily need to be in the code.



来源:https://stackoverflow.com/questions/5890617/understanding-pseudocode-to-construct-tree-from-preorder-traversal

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