Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/23.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
C++ 二叉树遍历为什么需要检查pre->;对!=现在的_C++_Algorithm_Binary Tree - Fatal编程技术网

C++ 二叉树遍历为什么需要检查pre->;对!=现在的

C++ 二叉树遍历为什么需要检查pre->;对!=现在的,c++,algorithm,binary-tree,C++,Algorithm,Binary Tree,在下面引用的二叉树遍历算法中,为什么需要检查第二个条件 pre->right!=当前的?这是循环条件吗?什么时候会发生这种情况 pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; 因为后一种代码是循环的(即子代码指向父代码): 但是,该循环稍后会被删除,但是pre->right!=当前测试tris以避免无休止地跟

在下面引用的二叉树遍历算法中,为什么需要检查第二个条件
pre->right!=当前的
?这是循环条件吗?什么时候会发生这种情况

  pre = current->left;
  while(pre->right != NULL && pre->right != current)
    pre = pre->right;

因为后一种代码是循环的(即子代码指向父代码):


但是,该循环稍后会被删除,但是
pre->right!=当前
测试tris以避免无休止地跟随循环。

考虑下面给出的树

    A
   / \
  B   C
 / \  /\
D  E F  G
作为根节点的节点A被初始化为当前节点。现在,您给出的代码试图找出in-inoreder遍历的直接前身。正如我们所知,给定树的顺序遍历如下所示

D  B  E  A  F  C  G 
因此,代码将E标识为A的直接前身。

[与您的假设树有关:

   A
  / \
 B   C
它的顺序是遍历=B,A,C

现在考虑,B已经被

打印出来了。
if(current->left == NULL)
    {
      printf(" %d ", current->data);
      current = current->right;
    }
因此,条件:

pre->right != current
需要中断while循环(有时可能是循环的),正好是我们的目标是打印节点
A

在这种情况下,在while循环的末尾,即
while(pre->right!=NULL&&pre->right!=current)
,我们将有:

1)
pre
指向左侧节点
B
-已打印
2)
current
指向中间节点
A
-在打印的旁边,这样就打破了我们为此创建的循环链接。下面的部分处理这个问题:

else
      {
        pre->right = NULL;           // Break cyclic link we've created for printing 'A'
        printf(" %d ",current->data);// prints 'A'
        current = current->right;    // Now, Aim for 'C'
      }

这是一个练习吗?算法来自哪里?
else
      {
        pre->right = NULL;           // Break cyclic link we've created for printing 'A'
        printf(" %d ",current->data);// prints 'A'
        current = current->right;    // Now, Aim for 'C'
      }