/**
* 199. Binary Tree Right Side View
* 1. Time:O(n) Space:O(n)
* 2. Time:O(n) Space:O(n)
*/
// 1. Time:O(n) Space:O(n)
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root,0,res);
return res;
}
public void helper(TreeNode root, int level, List<Integer> res){
if(root == null) return;
if(level == res.size())
res.add(root.val);
helper(root.right,level+1,res);
helper(root.left,level+1,res);
}
}
// 2. 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.add(root);
while(!queue.isEmpty()){
int cnt = queue.size();
for(int i=0;i<cnt;i++){
TreeNode tmp = queue.poll();
if(i==cnt-1)
res.add(tmp.val);
if(tmp.left!=null)
queue.add(tmp.left);
if(tmp.right!=null)
queue.add(tmp.right);
}
}
return res;
}
}
相关文章
- 03-16LeetCode 199: Binary Tree Right Side View
- 03-16leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II
- 03-16LeetCode OJ 199. Binary Tree Right Side View
- 03-16【LeetCode】199. Binary Tree Right Side View 解题报告(Python)
- 03-16(二叉树 bfs) leetcode 199. Binary Tree Right Side View
- 03-16199. Binary Tree Right Side View
- 03-16【原创】leetCodeOj --- Binary Tree Right Side View 解题报告
- 03-16[LeetCode] 1602. Find Nearest Right Node in Binary Tree
- 03-16【LeetCode】199. Binary Tree Right Side View
- 03-16LeetCode OJ:Binary Tree Right Side View(右侧视角下的二叉树)