-
Notifications
You must be signed in to change notification settings - Fork 0
199. Binary Tree Right Side View
Jacky Zhang edited this page Aug 29, 2016
·
2 revisions
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].
Tree类题目。
注意到每层有且仅有一个值,而且是每一层最靠近右边的。 可以采用DFS的思路,每次先traverse右孩子。如果level等于res的size,则把该值存入res,否则不是该层最靠右的。
/**
* 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<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
helper(root, 0, res);
return res;
}
private void helper(TreeNode node, int level, List<Integer> res) {
if(node == null) return;
if(level == res.size()) {
res.add(node.val);
}
helper(node.right, level+1, res);
helper(node.left, level+1, res);
}
}