【问题标题】:inorder binary search tree traversal for 1-101-10的中序二叉搜索树遍历
【发布时间】:2019-11-18 05:04:21
【问题描述】:

我正在用 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。但是,要么这个假设不正确,要么我的代码打印了不正确的输出。请让我知道我的输出是否正确,以及为什么正确。谢谢你。

【问题讨论】:

  • 您是否使用std::string 作为树键?因为如果这样做,"10" 确实大于"1" 但小于"2"。这是因为字符串是按字典顺序比较的。

标签: c++ binary-search-tree inorder


【解决方案1】:

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

(注意:我只为 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. 

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多