Leetcode of depth-first search (DFS) Thematic -199. Right view binary tree (Binary Tree Right Side View)

Leetcode of depth-first search (DFS) Thematic -199. Right view binary tree (Binary Tree Right Side View)

Problem-solving depth-first search details, click


 

Given a binary tree, to imagine standing on its own right, in order from the top in the end portion of the return value of the node can be seen from the right side.

Example:

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

   1 <--- 
 / \ 
23 <--- 
 \ \ 
  54 <---


Analysis: 
Save the value for each row up, and finally the last one into each row ans years.

AC Code:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> temp = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        if(root==null) return new ArrayList<Integer>();
        dfs(root,0);
        
        List<Integer> ans = new ArrayList<>();
        for(int i=0;i<temp.size();i++){
            List<Integer> list = temp.get(i);
            ans.add(list.get(list.size()-1));
        }
        return ans;
    }
    public void dfs(TreeNode node,int depth){
        if(node==null){
            return;
        }
        if(temp.size()==depth){
            temp.add(new ArrayList<>());
        }
        temp.get(depth).add(node.val);
        dfs(node.left,depth+1);
        dfs(node.right,depth+1);
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11367057.html