python 二叉树总结(一)


二叉树前中后遍历(深度优先)

前序遍历

# 递归法
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def Traversal(root):
            if root == None:
                return
            res.append(root.val)
            Traversal(root.left)
            Traversal(root.right)
        Traversal(root)
        return res
# 迭代法
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        stack = [root]
        res = []
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return res

后序遍历

# 递归法
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def Traversal(root):
            if root == None:
                return
            Traversal(root.left)
            Traversal(root.right)
            res.append(root.val)
        Traversal(root)
        return res
# 迭代法
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if root == None:
            return []
        stack = [root]
        res = []
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return res[::-1]

中序遍历

# 递归法
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def Traversal(root):
            if root == None:
                return
            Traversal(root.left)
            res.append(root.val)
            Traversal(root.right)
        Traversal(root)
        return  res
# 迭代法
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        stack = []  # 不能提前将root结点加入stack中
        res = []
        cur = root
        while cur or stack:
            # 先迭代访问最底层的左子树结点
            if cur:
                stack.append(cur)
                cur = cur.left
            # 到达最左结点后处理栈顶结点 
            else:
                cur = stack.pop()
                res.append(cur.val)
                # 取栈顶元素右结点
                cur = cur.right
        return res

前中后迭代统一遍历法:

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        res = []
        if root:
            stack.append(root)
        while stack:
            node = stack.pop()
            if node != None:
                stack.append(node)
                stack.append(None)
                
                if node.right:
                    stack.append(node.right)
                
                if node.left:
                    stack.append(node.left)
            else:
                node = stack.pop()
                res.append(node.val)
        return res

二叉树层序遍历(广度优先)

102.二叉树的层序遍历

迭代法:
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        if root == None:
            return res
        
        from collections import deque
        que = deque([root])

        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)
                
                if node.right:
                    que.append(node.right)
            res.append(result)

        return res
递归法:
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        def helper(node, depth):
            if node == None:
                return []
            if len(res) == depth:res.append([])
            res[depth].append(node.val)
            if node.left:
                helper(node.left, depth + 1)
            if node.right:
                helper(node.right, depth + 1)
        helper(root, 0)
        return res

107.二叉树的层次遍历II
从下至上就是把result倒过来

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return []
        res = []

        from collections import deque
        que = deque([root])
        
        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)

                if node.right:
                    que.append(node.right)
            res.append(result)
        return res[::-1]

199.二叉树的右视图
res 里 保存每个result 的最后一位就行

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        res = []
        if root == None:
            return res
        
        from collections import deque
        que = deque([root])
        
        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)

                if node.right:
                    que.append(node.right)
            
            res.append(result[-1])
        
        return res

637.二叉树的层平均值

class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        res = []
        if root == None:
            return res
        
        from collections import deque
        que = deque([root])
        
        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)

                if node.right:
                    que.append(node.right)
            
            res.append(sum(result) / len(result))
        
        return res

429.N叉树的层序遍历

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        res = []
        if root == None:
            return res
        
        from collections import deque
        que = deque([root])

        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.children:
                    que.extend(node.children)

            res.append(result)

        return res

515.在每个树行中找最大值

class Solution:
    def largestValues(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        if root == None:
            return res
        
        from collections import deque
        que = deque([root])
        
        while que:
            size = len(que)
            result = []
            for _ in range(size):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)

                if node.right:
                    que.append(node.right)
            
            res.append(max(result))
        
        return res

116.填充每个节点的下一个右侧节点指针

层序遍历法:
class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if root == None:
            return None
        
        from collections import deque
        que = deque([root])
        
        while que:
            n = len(que)
            for i in range(n):
                node = que.popleft()

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
                if i == n-1:
                    break
                    
                node.next = que[0]
        return root
链表:
class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return None
        head = root
        while head:
            cur = head
            while cur:
                if cur.left: cur.left.next = cur.right
                if cur.right and cur.next: cur.right.next = cur.next.left
                cur = cur.next
            head = head.left
        return root

117.填充每个节点的下一个右侧节点指针II

层序遍历:
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None
        
        from collections import deque
        que = deque([root])
        
        while que:
            size = len(que)
            for i in range(size):
                node = que.popleft()

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
                if i == size - 1:
                    break
                
                node.next = que[0]
        return root

104.二叉树的最大深度

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        res = []

        from collections import deque
        que = deque([root])
        
        while que:
            n = len(que)
            result = []
            for _ in range(n):
                node = que.popleft()
                result.append(node.val)

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
                
            res.append(result)
        
        return len(res)

111.二叉树的最小深度

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
            
        from collections import deque
        que = deque([(root, 1)])
        
        while que:
            size = len(que)
            for _ in range(size):
                node, depth = que.popleft()
                
                if node.left == None and node.right == None:
                    return depth
                
                if node.left:
                    que.append((node.left, depth + 1))
                if node.right:
                    que.append((node.right, depth + 1))
        
        return que[0][1]

翻转二叉树

层序遍历:
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None

        from collections import deque
        que = deque([root])

        while que:
            size = len(que)
            for _ in range(size):
                node = que.popleft()
                node.left, node.right = node.right, node.left

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
                
        return root
递归(前序)class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        def inver(node):
            if not node:
                return 
            node.left, node.right = node.right, node.left
            inver(node.left)
            inver(node.right)
        inver(root)
        return root

迭代(前序):
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        stack = [root]
        while stack:
            node = stack.pop()

            node.left, node.right = node.right, node.left
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值