Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Binary tree 理解伪代码从前序遍历构造树_Binary Tree_Pseudocode - Fatal编程技术网

Binary tree 理解伪代码从前序遍历构造树

Binary tree 理解伪代码从前序遍历构造树,binary-tree,pseudocode,Binary Tree,Pseudocode,我需要做一些类似于此问题中描述的任务: 这里有一个非常有用的答案,但我不完全理解伪代码,所以我想知道是否有人能帮我描述一下发生了什么 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 inpu

我需要做一些类似于此问题中描述的任务:

这里有一个非常有用的答案,但我不完全理解伪代码,所以我想知道是否有人能帮我描述一下发生了什么

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
是一个全局范围的变量,可在
recostruct(T)
中访问。它只是字符数组(输入字符串)的当前索引

正如您在引用的问题()中所解释的,正确的算法是先处理节点的左子节点,然后处理右子节点,这就是您在
if
true
部分中看到的。如果当前节点恰好是一个叶子,
L
,则不要给它子节点,并返回调用函数

此函数的作用是沿着树的左边缘,向所有
N
节点添加子节点,直到字符串结束,才向所有
L
节点(也称为叶子)添加子节点


编辑:当伪代码的作者说
T.left=T.right=null
时,这意味着此时,当前节点没有左或右子节点(因为它是一个叶子)。这只是一个断言,不一定要包含在代码中。

谢谢您的回答。那么,Reconstruct(T.left)和Reconstruct(T.right)是否再次调用该方法?或者它们只是在伪代码中编写,意味着我应该用代码替换它们,使其成为节点的左子节点,然后是右子节点?@Jigglypuff这些调用实际上是对同一个函数的调用。该算法是递归的。这些行应该像在实现中一样进行编码。谢谢。我真的很感谢你的帮助。