Table of contents
199. Right View of Binary Tree
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:
- First, we need to define a helper function
dfs
to do a depth-first search. This function receives the current noderoot
and the current layer numberdep
as parameters.- 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.- Next, we judge whether the current number of layers
dep
is greater than the maximum number of layers recordeddepth
. 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 listres
, and update the maximum number of layersdepth
.- 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.- 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.- 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: