首页 > 其他 > 详细

二叉树BST迭代器(非递归中序遍历)——Binary Search Tree Iterator

时间:2019-03-11 17:58:45      阅读:257      评论:0      收藏:0      [点我收藏+]

用栈来实现二叉树的非递归中序遍历

1、栈初始化:从根节点出发一路向左,将一路上的节点push到栈中

2、取next并进行栈的调整:从stack栈顶pop出来的节点即为要取的next节点。如果该节点有右孩子,则从该节点出发,往右走一步,再一路向左,将一路上的节点push进栈。

技术分享图片


class BSTIterator:
    """
    @param: root: The root of binary tree.
    """
    def __init__(self, root):
        self.stack = []
        while root != None:
            self.stack.append(root)
            root = root.left

    """
    @return: True if there has next node, or false
    """
    def hasNext(self):
        return len(self.stack) > 0

    """
    @return: return next node
    """
    def next(self):
        node = self.stack.pop()
        cur = node.right
        while cur is not None:
            self.stack.append(cur)
            cur = cur.left
        return node

 

二叉树BST迭代器(非递归中序遍历)——Binary Search Tree Iterator

原文:https://www.cnblogs.com/liqiniuniu/p/10511845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!