1.简述:
给定一棵二叉树 根节点 root,想象自己站在它的右边,按照从顶部到底部的顺序返回从右边看到的节点值。
示例 1:
输入:[1,2,3,null,5,null,4]
输出:[1,3,4]
示例 2:
输入:[1,null,3]
输出:[1,3]
示例 3:
输入:[]
输出:[]
2.实现代码:
class Solution { public List<Integer> rightSideView(TreeNode root) { Map<Integer, Integer> rightmostValueAtDepth = new HashMap<Integer, Integer>(); int max_depth = -1; Deque<TreeNode> nodeStack = new LinkedList<TreeNode>(); Deque<Integer> depthStack = new LinkedList<Integer>(); 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 (!rightmostValueAtDepth.containsKey(depth)) { rightmostValueAtDepth.put(depth, node.val); } nodeStack.push(node.left); nodeStack.push(node.right); depthStack.push(depth + 1); depthStack.push(depth + 1); } } List<Integer> rightView = new ArrayList<Integer>(); for (int depth = 0; depth <= max_depth; depth++) { rightView.add(rightmostValueAtDepth.get(depth)); } return rightView; }}