【问题标题】:How can I traverse binary search tree without recursion?如何在没有递归的情况下遍历二叉搜索树?
【发布时间】:2015-10-08 17:33:48
【问题描述】:

我可以轻松地使用递归遍历二叉搜索树,但是我不知道不使用递归进行遍历,所以请任何人解释一下,.....

【问题讨论】:

  • 一开始你有没有自己尝试过。请把代码贴在你卡住的地方。
  • 您可能应该阅读Tree Traversal 上的维基百科页面,那里有多种算法来说明如何使用和不使用递归。

标签: recursion tree binary-search-tree traversal


【解决方案1】:

是的,你可以用堆栈来做到这一点。您必须在此处以二叉搜索树的迭代方式(非递归方式/方法)进行预排序、中序和后序遍历的算法。希望你能好好的。

预购:

1) 创建一个空栈node_Stack,并将根节点压入栈。

2) 在 node_Stack 不为​​空时执行以下操作。

-> 从堆栈中弹出一个项目并打印它。

-> 将弹出项的右孩子推入堆栈

-> 将弹出项的左孩子压入堆栈

按顺序:

1) 创建一个空栈S。

2) 将当前节点初始化为root

3) 将当前节点推入S并设置current = current->left,直到current为NULL

4) 如果 current 为 NULL 且堆栈不为空,则

 -> Pop the top item from stack.

 -> Print the popped item, set current = popped_item->right 

 -> Go to step 3.

5) 如果 current 为 NULL 并且堆栈为空,那么我们就完成了。

下单:

1.1 创建一个空栈

2.1 在 root 不为 NULL 时执行以下操作

-> Push root's right child and then root to stack.

-> Set root as root's left child.

2.2 从堆栈中弹出一个项目并将其设置为根。

-> If the popped item has a right child and the right child 
   is at top of stack, then remove the right child from stack,
   push the root back and set root as root's right child.

-> Else print root's data and set root as NULL.

2.3 堆栈不为空时重复步骤 2.1 和 2.2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 2020-09-25
    • 2013-05-12
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多