199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].

一刷
题解:用递归来求解,里面最巧妙的是,递归子问题内传入了level, 如果level与我们当前的array的size想同,那么它就不是rightmost

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List rightSideView(TreeNode root) {
        List res = new ArrayList<>();
        rightView(root, 0, res);
        return res;
    }
    
    private void rightView(TreeNode root, int level, List res){
        if(root==null) return;
        if(level == res.size()) res.add(root.val);
        rightView(root.right, level+1, res);
        rightView(root.left, level+1, res);
    }
}

二刷
其实就是DFS,但是要加上一个level的信息,来决定是否加入结果中。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List rightSideView(TreeNode root) {
        List res = new ArrayList<>();
        if(root == null) return res;
        rightView(root, 1, res);
        return res;
        
    }
    
    private void rightView(TreeNode root, int level, List res){
        if(root == null) return;
        if(level>res.size()) res.add(root.val);
        rightView(root.right, level+1, res);
        rightView(root.left, level+1, res);
    }
}

三刷
DFS + level信息

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List rightSideView(TreeNode root) {
        List res = new ArrayList<>();
        rightSideView(root, 1, res);
        return res;
    }
    
    private void rightSideView(TreeNode root, int level, List res){
        if(root == null) return;
        if(level>res.size()){
            res.add(root.val);
        }
        rightSideView(root.right, level+1, res);
        rightSideView(root.left, level+1, res);
    }
}

你可能感兴趣的:(199. Binary Tree Right Side View)