繁体   English   中英

1-10的中序二叉搜索树遍历

[英]inorder binary search tree traversal for 1-10

我在 C++ 中做一个简单的二叉搜索树实现。 我发现它适用于大多数测试用例,但我对创建树并按顺序添加 1、2、3、4、5、6、7、8、9、10 的测试用例感到困惑。 中序遍历结果为 1,10,2,3,4,5,6,7,8,9。 我的理解是中序遍历将按排序顺序打印元素,即 1,2,3,4,5,6,7,8,9,10。 但是,要么这个假设不正确,要么我的代码打印了不正确的 output。 请让我知道我的 output 是正确还是错误,以及为什么正确。 谢谢你。

如果您不确定二叉树遍历的顺序如何工作,请查看下面的树和解释。

(注意:我只为 5 个号码做了这个)。

 /* Constructed binary tree is 
              1 
            /   \ 
          2      3 
        /  \ 
      4     5 
    */

Step 1 Creates an empty stack: S = NULL

Step 2 sets current as address of root: current -> 1

Step 3 Pushes the current node and set current = current->left until current is NULL
     current -> 1
     push 1: Stack S -> 1
     current -> 2
     push 2: Stack S -> 2, 1
     current -> 4
     push 4: Stack S -> 4, 2, 1
     current = NULL

Step 4 pops from S
     a) Pop 4: Stack S -> 2, 1
     b) print "4"
     c) current = NULL /*right of 4 */ and go to step 3
Since current is NULL step 3 doesn't do anything. 

Step 4 pops again.
     a) Pop 2: Stack S -> 1
     b) print "2"
     c) current -> 5/*right of 2 */ and go to step 3

Step 3 pushes 5 to stack and makes current NULL
     Stack S -> 5, 1
     current = NULL

Step 4 pops from S
     a) Pop 5: Stack S -> 1
     b) print "5"
     c) current = NULL /*right of 5 */ and go to step 3
Since current is NULL step 3 doesn't do anything

Step 4 pops again.
     a) Pop 1: Stack S -> NULL
     b) print "1"
     c) current -> 3 /*right of 5 */  

Step 3 pushes 3 to stack and makes current NULL
     Stack S -> 3
     current = NULL

Step 4 pops from S
     a) Pop 3: Stack S -> NULL
     b) print "3"
     c) current = NULL /*right of 3 */  

Traversal is done now as stack S is empty and current is NULL. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM