p199

LeetCode p199 Binary Tree Right Side View 题解

1.题目:

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].

题意:

给你一个二叉树,返回它从右边看过去是一个什么样的列表。【从上往下排列】

2.解题思路:

见代码
搜索最右。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
/**
* 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> ans = new ArrayList<Integer>();
helper(root, 0, ans);
return ans;
}

public void helper(TreeNode root, int j, List<Integer> ans) {

if (root == null)
return;
if (ans.size() <= j)
ans.add(root.val);
helper(root.right, j + 1, ans);
helper(root.left, j + 1, ans);
}
}


4.一些总结: