LeetCode.199 Binary Tree Right Side View

本文介绍了一种算法,用于获取二叉树从顶部到底部的右侧可见节点值。通过两种方法实现:迭代(使用队列)和递归。递归方法更简洁,通过对左右子树高度的判断,确保每个层级只返回一个节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

For example:
Given the following binary tree,

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

You should return [1, 3, 4].

分析:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //给定一棵二叉树,假设你站在树的右边,返回你从树根到最下面的节点数
        //思路:每次都访问右子树,一次从根节点访问到叶子结点。如果右子树不存在,则访问左子树(采用类似层序遍历的方法,每次取每一层的第一个数据)
        //注意:需要判断左右子树的高度,来觉得访问结点个数
        List<Integer> list=new ArrayList<Integer>();
        if(root==null) return list;
        
        Queue<TreeNode> qu=new LinkedList<TreeNode>();
        qu.add(root);
        while(!qu.isEmpty()){
            //每层取第一个数据
            int size=qu.size();
            //因为size已经是个定值,如果在for中定义,qu的长度会变化,循环长度就不确定了
            for(int i=0;i<size;i++){
                TreeNode cur=qu.poll();
                if(i==0){
                    list.add(cur.val);
                }
                if(cur.right!=null) qu.add(cur.right);
                if(cur.left!=null) qu.add(cur.left);
            }
        }
        
        return list;
        
    }
}

分析2(递归实现):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //给定一棵二叉树,假设你站在树的右边,返回你从树根到最下面的节点数
        //思路2:采用递归实现,对左右子树高度进行判断。
        //注意:需要判断左右子树的高度,来决定访问结点。只有当左右子树高度刚好等于结点所在,才返回该结点的值
        
        List<Integer> list=new ArrayList<Integer>();
        if(root==null) return list;
        //当前根节点深度为0
        backtrace(root,list,0);
        return list;
    }
    //递归实现
    public void backtrace(TreeNode root,List<Integer> result,int curDepth){
        if(root==null){
            return ;
        }
        
        if(curDepth==result.size()){
            //高度相同
            result.add(root.val);
        }
        
        //对左右子树递归,每层高度只取一个(一般为最右边的,如若右边不存在,则取左边的)
        backtrace(root.right,result,curDepth+1);
        backtrace(root.left,result,curDepth+1);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值