Leetcode 199: 二叉树的右视图

题目

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

1 <—
/
2 3 <—
\
5 4 <—

解法

解法一:
层序遍历,然后记录每层中最后一个元素

    public List<Integer> rightSideView2(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null) return list;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        LinkedList<TreeNode> tmp = new LinkedList<>();
        while(!queue.isEmpty()){
            TreeNode pre = null;
            while(!queue.isEmpty()){
                pre = queue.poll();
                if(pre.left != null) tmp.offer(pre.left);
                if(pre.right != null) tmp.offer(pre.right);
            }
            list.add(pre.val);
            queue.addAll(tmp);
            tmp.clear();
        }
        return list;
    }

解法二:
深度优先遍历,最早访问到的第i层的元素,放入list中。

    public List<Integer> rightSideView(TreeNode root) {
        // im a super super super idiot
        List<Integer> list = new ArrayList<>();
        helper(root, 0, list);
        return list;
    }
    
    private void helper(TreeNode root, int depth, List<Integer> list){
        if(root == null) return ;
        if(list.size() <= depth){
            list.add(root.val);
        }
        helper(root.right, depth + 1, list);
        helper(root.left, depth + 1, list);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值