您的位置:首页 > 其它

【LeetCode】199.Binary Tree Right Side View(Medium)解题报告

2018-03-17 19:51 405 查看
【LeetCode】199.Binary Tree Right Side View(Medium)解题报告

题目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/

题目描述:

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


Solution1:

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


Solution2:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
time : O(n)
space : O(n)
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0 ; i<size ; i++){
TreeNode cur = queue.poll();
if(i == 0) res.add(cur.val);
if(cur.right!=null) queue.offer(cur.right);
if(cur.left!=null) queue.offer(cur.left);
}
}
return res;
}
}


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