Binary Tree Preorder Traversal (Python)
Binary Tree Postorder Traversal (Python)

Binary Tree Inorder Traversal (Python)

kitt posted @ 2014年2月12日 20:55 in LeetCode , 2406 阅读

二叉树的非递归中序遍历, 请看此文, 总结得非常好, 前序非递归还可以再简单一些, 一开始root在栈中, 然后while循环只要栈不空, 弹栈print, 右子节点入栈, 左子节点入栈即可。

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def inorderTraversal(self, root):
        res = []; stack = []
        while root or stack:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                res.append(root.val)
                root = root.right
        return res

以下做法速度更快, 但是不太好理解:

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def inorderTraversal(self, root):
        res = []
        stack = []
        p = root
        while p or stack:
            while p: stack.append(p); p = p.left
            p = stack.pop()
            res.append(p.val)
            p = p.right
        return res

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter