LeetCode Binary Tree Inorder Traversal

Posted yangykaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Binary Tree Inorder Traversal相关的知识,希望对你有一定的参考价值。

LeetCode解题之Binary Tree Inorder Traversal


原题

不用递归来实现树的中序遍历。

注意点:

样例:

输入: {1,#,2,3}

   1
         2
    /
   3

输出: [1,3,2]

解题思路

通过栈来实现,从根节点開始,不断寻找左节点,并把这些节点依次压入栈内。仅仅有在该节点没有左节点或者它的左子树都已经遍历完毕后,它才会从栈内弹出,这时候訪问该节点,并它的右节点当做新的根节点一样不断遍历。

AC源代码

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        result = []
        stack = []
        p = root
        while p or stack:
            # Save the nodes which have left child
            while p:
                stack.append(p)
                p = p.left
            if stack:
                p = stack.pop()
                # Visit the middle node
                result.append(p.val)
                # Visit the right subtree
                p = p.right
        return result


if __name__ == "__main__":
    n1 = TreeNode(1)
    n2 = TreeNode(2)
    n3 = TreeNode(3)
    n1.right = n2
    n2.left = n3
    assert Solution().inorderTraversal(n1) == [1, 3, 2]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

以上是关于LeetCode Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Binary search tree --Binary Search Tree Iterator

Leetcode[110]-Balanced Binary Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

LeetCode 110. Balanced Binary Tree 递归求解

[Leetcode] Balanced Binary Tree