我需要做一些类似于这个问题中描述的任务:
根据给定的前序遍历构造树 https://stackoverflow.com/questions/4908545/construct-tree-with-pre-order-traversal-given
这里有一个非常有用的答案,但我不完全理解伪代码,所以我想知道是否有人可以帮助向我描述发生了什么。
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
我已经在评论中写下了我对事物的理解,如果有人能够检查我的理解是否正确以及问号位的作用,我将非常感激。另外,这个伪代码是否通过运行输入并在输入中遇到 L 时回溯来创建一棵新树?或者重建现有的二叉树?
没有循环。k
是一个全局范围的变量,可以在Reconstruct(T)
。它只是字符数组(输入字符串)的当前索引。
正如您引用的问题中所解释的(通过先序遍历构造树 https://stackoverflow.com/questions/4908545/construct-tree-with-pre-order-traversal-given),正确的算法是先计算节点的左子节点,然后再计算右子节点,这就是您在true
的部分if
。如果当前节点恰好是叶子节点,L
,然后不给它子级并返回到调用函数。
这个函数的作用是沿着树的左边缘,将子节点添加到所有树中N
节点并且不向所有节点添加子节点L
节点(又名叶子)直到字符串结束。
编辑:当伪代码的作者说T.left = T.right = null
,表示此时当前节点没有左子节点或右子节点(因为它是叶子节点)。这只是一个断言,不一定需要出现在代码中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)