- 二叉树的右视图
题目
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <—
/
2 3 <—
\
5 4 <—
思路
主要思路是依次(根,左,右)将节点压入栈内,再用一个栈存储节点对应的深度。用一个HashMap存储一层的最右边的节点。从栈内取出节点和深度。更新维护当前最大深度,如果Map内还没有键为对应深度的节点,则将其加入Map。并将其左右子节点分别压入堆栈。持续该过程直至栈为空。然后将map内的结果转移至结果数组。
代码
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Map<Integer, TreeNode> rightMostVlaue = new HashMap<>();
int max_depth = -1;
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> depthStack = new Stack<>();
nodeStack.push(root);
depthStack.push(0);
while (!nodeStack.isEmpty()) {
TreeNode node = nodeStack.pop();
int depth = depthStack.pop();
if (node != null) {
max_depth = Math.max(max_depth, depth);
if (!rightMostVlaue.containsKey(depth)) {
rightMostVlaue.put(depth, node);
}
nodeStack.push(node.left);
nodeStack.push(node.right);
depthStack.push(depth + 1);
depthStack.push(depth + 1);
}
}
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= max_depth; i++) {
res.add(rightMostVlaue.get(i).val);
}
return res;
}
}