LeetCode199. 二叉树的右视图

题目

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

例如:
给定以下二叉树,

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

你应该返回 [1, 3, 4]


分析

首先把二叉树的根节点添加到list结果集合中,然后遍历二叉树,首先遍历它的右子树,当结果添加一个之后,给deep+1,代表当前的最右侧的数的深度。每遍历一层的时候都要先给temp+1,代表当前树的深度。

当temp<deep的时候,不符合题意,所以不添加入结果集,继续遍历,

当temp > deep 的时候,符合题意, 加入结果街。

还有temp = deep时,需要判断一下是不是最右边的树,如果是最右边的树则加入list,如果不是,则不加入。


代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    static boolean flag = true;//是否还存在最右边的树
    static int deep = 0;
    
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null)
            return list;
        list.add(root.val);
        deep = 0;
        flag = true;
        iterator(root,list,0);
        return list;
    }
    
    public static void iterator(TreeNode root, List<Integer>list, int temp){
        temp++;
        if (root.right != null){
            if (temp >deep || (temp == deep && flag)){
                list.add(root.right.val);
                deep++;
            }
            iterator(root.right,list,temp);
        }else
            flag = false;//最右边遍历完毕,flag==false了之后 当temp==deep的时候 则不符合条件

        if (root.left != null){
            if (temp > deep || (temp == deep && flag)){
                list.add(root.left.val);
                deep++;
            }
            iterator(root.left,list,temp);
        }
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值