标签:self code nod 返回 控制 batch maximum proc 队列
102. 二叉树的层次遍历 https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
解:
利用队列实现bfs,从根节点开始入队,如果左右子树不空,就入队。把每层的所有节点都遍历完了,下一层的最左节点再出队。(用for循环控制即可,因为在开始遍历新的一层之前,queue中只存了这一层的全部节点,batch process)。O(N)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        
        queue = [root]
        # visited = set(root) # 二叉树不需要visited标志,但图需要
        res = []
        while queue:
            tmp = []
            for _ in range(len(queue)):
                node = queue.pop(0)
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(tmp)
        return res
dfs解决,开拓一下思路,递归的不断把level放下去,就把dfs遍历到的每个节点按level灌到res里面即可。
104. 二叉树的最大深度 https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
解:
最直接的思路,递归实现,每个节点的深度为max(left, right) +1
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
标签:self code nod 返回 控制 batch maximum proc 队列
原文地址:https://www.cnblogs.com/chaojunwang-ml/p/11360440.html