【问题标题】:python how to traversal a binary search tree using inorder/pre/post/ without recursion?python如何使用inorder/pre/post/遍历二叉搜索树而不递归?
【发布时间】:2016-11-15 15:16:16
【问题描述】:

在python 3中

class BinaryTree:
"""
=== Private Attributes ===
@type _root: object | None
@type _left: BinaryTree | None
@type _right: BinaryTree | None

"""
def __init__(self, root, left, right):

    if root is None:
        # store an empty BinaryTree
        self._root = None
        self._left = None
        self._right = None
    else:
        self._root = root
        self._left = left
        self._right = right

def is_empty(self):
    return self._root is None

我知道如何递归遍历这棵二叉树,但我想知道如何在没有递归的情况下做到这一点

【问题讨论】:

标签: python python-3.x tree


【解决方案1】:

您可以使用堆栈方法进行树遍历而无需递归。 我正在举例说明

def inOrder(root):

    # Set current to root of binary tree
    current = root 
    s = [] # initialze stack
    done = 0

    while(not done):

        # Reach the left most Node of the current Node
        if current is not None:

            # Place pointer to a tree node on the stack 
            # before traversing the node's left subtree
            s.append(current)

            current = current.left 


        # BackTrack from the empty subtree and visit the Node
        # at the top of the stack; however, if the stack is 
        # empty you are done
        else:
            if(len(s) >0 ):
                current = s.pop()
                print current.data,

                # We have visited the node and its left 
                # subtree. Now, it's right subtree's turn
                current = current.right 

            else:
                done = 1

更多解释可以参考https://www.youtube.com/watch?v=xLQKdq0Ffjg&t=755s教程

【讨论】:

  • 不错!那么预购和后购是否遵循类似的模式?
  • 他们也将使用堆栈,但模式不同。您可以观看给定的 youtube 视频以了解更多有关预购和后购的信息。
猜你喜欢
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 2016-01-22
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多