美文网首页
94. Binary Tree Inorder Traversa

94. Binary Tree Inorder Traversa

作者: 羲牧 | 来源:发表于2020-06-10 22:35 被阅读0次

    首先是递归Recursive的解法

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            if root is None:
                return []
            result = []
            if root.left is not None:
                result += self.inorderTraversal(root.left)
            result.append(root.val)
            if root.right is not None:
                result += self.inorderTraversal(root.right)
            return result
            
    

    非递归的解法一,使用栈。根节点先入栈,然后循环将其所有左节点全部入栈。
    然后从栈顶弹出一个元素并记录到输出,然后访问这个元素的右节点,循环。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            if root is None:
                return []
            
            result = []
            p = root
            stack = []
            while p or len(stack) > 0:
                while p:
                    stack.append(p)
                    p = p.left
                p = stack[-1]
                stack.pop()
                result.append(p.val)
                p = p.right
            return result
            
    

    改写一下上面的写法,看起来更加直观:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            if root is None:
                return []
            
            result = []
            p = root
            stack = []
            while p or len(stack) > 0:
                if p:
                    stack.append(p)
                    p = p.left
                else:
                    p = stack[-1]
                    stack.pop()
                    result.append(p.val)
                    p = p.right
            return result
            
    

    还有一种线索二叉树的解法,留待下一轮刷题
    https://www.cnblogs.com/grandyang/p/4297300.html

    相关文章

      网友评论

          本文标题:94. Binary Tree Inorder Traversa

          本文链接:https://www.haomeiwen.com/subject/hspmtktx.html