LeetCode algorithm recursive class - the right view of the binary tree

Table of contents

199. Right View of Binary Tree

answer:

Target:

Ideas:

process:

code:

operation result:


Given  the root node root of a binary tree , imagine yourself standing on the right side of it, in order from top to bottom, return the node values ​​​​that can be seen from the right side.

Example 1:

Input:  [1,2,3,null,5,null,4]
 Output:  [1,3,4]

Example 2:

Input:  [1,null,3]
 Output:  [1,3]

Example 3:

Input:  []
 Output:  []

hint:

  • The range of the number of nodes in a binary tree is [0,100]
  • -100 <= Node.val <= 100  

answer:

Target:

Observing from the right side of the binary tree, return the list of node values ​​​​that can be seen, that is, the red part

 (The picture uses the problem-solving icon on Leetow’s official website)

Ideas:

Depth-first traversal of the tree , using root-right-left order, always visits the right subtree first . Then for each layer, the first node we see in this layer must be the rightmost node.

So if we store the first node visited at each depth , once we know the number of levels in the tree, we can get the final result array.

process:

  1. First, we need to define a helper function  dfs to do a depth-first search. This function receives the current node  root and the current layer number  dep as parameters.
  2. In  dfs the function, we first judge whether the current node is empty, and return directly if it is empty. This is the termination condition.
  3. Next, we judge whether the current number of layers  dep is greater than the maximum number of layers recorded  depth. If it is, then the current layer is the node that can be seen for the first time from the right side, add its value to the result list  res , and update the maximum number of layers  depth.
  4. Then, we recursively call  dfs the function to perform a depth-first search on the right child node, passing in the value of the current level plus 1 as a parameter.
  5. Call  dfs the function recursively again to perform a depth-first search on the left child node, and also pass in the value of the current layer plus 1 as a parameter.
  6. Finally, a list of results is returned  res.

code:

class Solution {
    // 记录结果
    List<Integer> res=new ArrayList<>();
    // 辅助记录树的层数
    int depth=-1;
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) return res; // 处理根节点为空的情况
        dfs(root,0);
        return res;
    }
    public void dfs(TreeNode root,int dep){
        if(root==null) return;
        if(depth<dep){
            res.add(root.val);
            depth++; 
        }
        dfs(root.right,dep+1);
        dfs(root.left,dep+1);
        return;
    }
}

operation result:

 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132393498