描述:
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
思路分析:
强行使用DFS,感觉也可以使用BFS的层次分析,保存每一层的最后一个元素就可以了。
代码实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> ans = new ArrayList<>();
public void robot(int idx, TreeNode node) {
if (node == null) {
return;
}
if (ans.size() <= idx) {
ans.add(node.val);
} else {
ans.set(idx, node.val);
}
robot(idx + 1, node.left);
robot(idx + 1, node.right);
}
public List<Integer> rightSideView(TreeNode root) {
ans.clear();
robot(0, root);
return ans;
}
}