Leetcode-dfs & bfs

102. The binary tree hierarchy traversal  https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

Given a binary tree, the node returns its value hierarchical traversal. (Ie, layer by layer, from left to right to access all nodes).

solution:

Use queue implementation bfs, start from the root into the team, if the left and right subtrees are not empty, into the team. All nodes are each traversed over, the left-most node next level again from the team. (For loop control can, because before traversing a new layer, queue only keep all the nodes in this layer, 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 solve, explore ideas about recursion level continues to go down, put each node dfs traversed by irrigation level to which you can res.

 

 

 

104. Binary Tree is the maximum depth  https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

Given a binary tree to find its maximum depth.

The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.

Description: leaf node is a node has no child nodes.

solution:

The most direct way of thinking, recursive implementation, the depth of each node is 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

  

 

Guess you like

Origin www.cnblogs.com/chaojunwang-ml/p/11360440.html
Recommended