https://leetcode-cn.com/problems/binary-tree-right-side-view/submissions/
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null){
return new ArrayList<>();
}
addHelper(root,0,result);
return result;
}
public static void addHelper(TreeNode root,int level,List<Integer> result){
if (root == null){
return;
}
if (level == result.size()){
result.add(null);
}
if (result.get(level) == null){
result.remove(level);
result.add(root.val);
}else {
result.remove(level);
result.add(level,root.val);
}
if (root.left != null){
addHelper(root.left,level+1,result);
}
if (root.right != null){
addHelper(root.right,level+1,result);
}
}
}