[LeetCode199] Right View of Binary Tree (Level Traversal or DFS)

Article directory

1. Topic

insert image description here

Two, ideas

  • The most intuitive is to traverse the level, and then store the first element of each level into the result list
  • If dfs is used to access nodes in the order of (root node, right subtree, left subtree); according to the rules of the topic, only the rightmost node will be extracted in each layer. If the current depth is equal to the size of the result array, then This is the first time the layer is visited and the current node satisfies the condition.

3. Code

# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        queue = [root]
        res = []
        while queue: 
            width = len(queue)
            for i in range(width):
                # 队列头部,索引为0处pop一个元素
                node = queue.pop(0)
                # 符合条件的节点
                if i == width - 1:
                    res.append(node.val)
                if node.left: 
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return res          

Method 2: python code of dfs

# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        start_depth = 0
        res = []
        def dfs(node, depth): 
            if not node:
                return 
            if depth == len(res):
                res.append(node.val)
            dfs(node.right, depth+1)
            dfs(node.left, depth+1)

        dfs(root, start_depth)
        return res 

Guess you like

Origin blog.csdn.net/qq_35812205/article/details/130912280