您的位置:首页 > 其它

199. Binary Tree Right Side View

2016-04-19 02:09 309 查看
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]
.

Solution 1

// BFS
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
if (root == null) {
return res;
}
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode temp = q.poll();
if (i == size - 1) {
res.add(temp.val);
}
if (temp.left != null) {
q.offer(temp.left);
}
if (temp.right != null) {
q.offer(temp.right);
}
}
}
return res;
}


Solution 2

//Better DFS
public static List<Integer> rightSideView2(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
rightView(root, result, 0);
return result;
}

public static void rightView(TreeNode curr, List<Integer> result, int currDepth) {
if (curr == null) {
return;
}
if (currDepth == result.size()) {
result.add(curr.val);
}

rightView(curr.right, result, currDepth + 1);
rightView(curr.left, result, currDepth + 1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: