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:从右侧 pre-order DFS 递归写法
思路: 每层只加第一次,通过cur_level和result.length控制
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution2: BFS 从右侧push
思路: 每层只加第一个。 当然从左边开始push也一样,只加最后
Time Complexity: O(N) Space Complexity: O(N)
Solution3: Divide and Conquer (not efficient, only for demo)
Time Complexity:
if nearly balance, T(N) = 2T(N/2) + logN => O(N) ?
worst: O(N^2)
Space Complexity: O(N)
Solution1 Code:
class Solution1 {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
rightView(root, result, 0);
return result;
}
public void rightView(TreeNode curr, List<Integer> result, int cur_level){
if(curr == null) return;
if(cur_level == result.size()){
result.add(curr.val);
}
rightView(curr.right, result, cur_level + 1);
rightView(curr.left, result, cur_level + 1);
}
}
Solution2 Code:
class Solution2 {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()) {
int num_on_level = queue.size();
for(int i = 0; i < num_on_level; i++) {
TreeNode cur = queue.poll();
if(i == 0) result.add(cur.val);
if(cur.right != null) queue.add(cur.right);
if(cur.left != null) queue.add(cur.left);
}
}
return result;
}
}
Solution3 Code:
class Solution3 {
public List<Integer> rightSideView(TreeNode root) {
if(root==null)
return new ArrayList<Integer>();
List<Integer> left = rightSideView(root.left);
List<Integer> right = rightSideView(root.right);
List<Integer> re = new ArrayList<Integer>();
re.add(root.val);
for(int i=0;i < Math.max(left.size(), right.size()); i++){
if(i >= right.size())
re.add(left.get(i));
else
re.add(right.get(i));
}
return re;
}
}