【笔试面试】研发岗面试算法高频题

15 篇文章 0 订阅
14 篇文章 0 订阅
  1. 二叉树的右视图

题目

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

输入: [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;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值