Binary Tree Right Side View
Approach 1: BFS
/* The last node that we encounter at a particular depth contains
* the correct value, so the correct value is never overwritten. */
rightmostValueAtDepth.put(depth, node.val);
例子:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
使用BFS, 把同一depth 的node 存在同一个stack。
- root: [1] , list: [1]
- level 1: [2, 3] , list:[1, 3]
- level2: [null , 5 , null, 4] , list:[1,3,4]
- return list:[1,3,4]
Approach 2: DFS
The first time we visit a particular depth of the tree, the node that we are visiting is the rightmost node at that depth.
/* The first node that we encounter at a particular depth contains
* the correct value. */
if (!rightmostValueAtDepth.containsKey(depth)) {
rightmostValueAtDepth.put(depth, node.val);
}
Approach 3: Recursive Traverse Tree
if(currDepth == result.size()){
result.add(curr.val);
}
用res的size判断层数。
例子:
Input: [1,2,3,null,5, 4, null]
Output: [1, 3, 4]
- root: [1 add]
- level1: [2, 3 add]
- level2: [null, 5, 4 add, null retrun ]