首页 > 代码库 > [leetcode]Binary Tree Inorder Traversal @ Python

[leetcode]Binary Tree Inorder Traversal @ Python

原题地址:http://oj.leetcode.com/problems/binary-tree-inorder-traversal/

题意:二叉树的中序遍历。

解题思路:这道题用递归解不难,所以应该考察的是非递归求解二叉树的中序遍历。我们使用一个栈来解决问题。比如一颗二叉树为{1,2,3,4,5,6,7},第一层为{1},第二层为{2,3},第三层为{4,5,6,7}。那么我们依次存储左子树的根节点,那么入栈顺序为:1,2,4。由于4的左子树为空,所以开始出栈。4出栈,检查4的右子树为空,继续出栈,2出栈后,2的右子树非空,5入栈,5的左子树为空,5出栈,由于5的右子树为空,继续出栈,1出栈后,发现1的右子树非空,3入栈。。。依次类推,就完成了非递归(迭代)解法。

代码:

# Definition for a  binary tree node
# 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 iterative_inorder(self, root, list):
        stack = []
        while root or stack:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                list.append(root.val)
                root = root.right
        return list
                
    def recursive_inorder(self, root, list):
        if root:
            self.inorder(root.left, list)
            list.append(root.val)
            self.inorder(root.right, list)
        
    def inorderTraversal(self, root):
        list = []
        self.iterative_inorder(root, list)
        return list