美文网首页
leetcode 144 145 94

leetcode 144 145 94

作者: 就是果味熊 | 来源:发表于2020-08-17 18:12 被阅读0次

    二叉树遍历

    前序遍历

    非递归
    class Solution:
        def preorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            stack = []
            if not root:
                return res
            stack.append(root)
            
            while stack:
                item = stack.pop()
                res.append(item.val)
                if item.right:
                    stack.append(item.right)
                if item.left:
                    stack.append(item.left)
            return res
    递归
    class Solution:
        def postorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            def dfs(root):
                if not root:
                    return
                res.append(root.val)
                dfs(root.left)
                dfs(root.right)
            dfs(root)
            return res
    

    中序遍历

    非递归
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            stack = []
            
            while stack or root:
                while root:
                    stack.append(root)
                    root = root.left
                root = stack.pop()
                res.append(root.val)
                root = root.right
            return res
    递归
    class Solution:
        def postorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            def dfs(root):
                if not root:
                    return
                dfs(root.left)
                res.append(root.val)
                dfs(root.right)
            dfs(root)
            return res
    
    

    后序遍历

    非递归
    class Solution:
        def postorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            stack = []
            if not root: return res
            stack.append(root)
            while stack:
                item = stack.pop()
                res.append(item.val)
                if item.left:
                    stack.append(item.left)
                if item.right:
                    stack.append(item.right)
            
            return reversed(res)
    
    递归
    class Solution:
        def postorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            def dfs(root):
                if not root:
                    return
                dfs(root.left)
                dfs(root.right)
                res.append(root.val)
            dfs(root)
            return res
    

    相关文章

      网友评论

          本文标题:leetcode 144 145 94

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