总论
Scenario
二叉树的右视图
Assumption
就普通一个二叉树,不是二叉搜索树(是的话也跟这题没啥关系),不必要是满树、完全树等等;但这些问题你有可以跟面试官确认下。
Input/Output
先给LeetCode上的例子:
1
2 3
5 4
[1, 3, 4]
我一开始看这例子以为只要拿个while循环root.right.right…就好了,但哪里可能这么简单?!
1
2 3
5
[1, 3, 5]
想法1
Top down approach to traverse the tree. For each level traversed, save the rightmost node into the result set, and we need to pass this result set to the next level.
This is similar to pre-order traversal of the tree. But the order would be (root, right, left) cuz we want the right side view, and the right side has priority over the left side.
难点:如何保证每一层只存一个最右边的Node?树的深度与ResultSet的Size同步化。
Idea 1 代码
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
rightView(root, ret, 0);
return ret;
}
public static void rightView(TreeNode root, List<Integer> ret, int depth) {
if(root == null) {
return;
}
if(depth == ret.size()) {
ret.add(root.val);
}
rightView(root.right, ret, depth + 1);
rightView(root.left, ret, depth + 1);
}
由于我是小弱,所以把递归过程用图画了一遍,加深理解: