199. Binary Tree Right Side View

本文深入探讨了二叉树右视图算法的实现原理,通过递归方式记录每一层最右侧节点的值,从顶部到底部展示二叉树的右侧面。算法采用类似于后序遍历的方式,先右子树后左子树,确保每层的最后一个节点被记录。

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

Description

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 <—

Problem URL


Solution

给一棵二叉树,返回这棵二叉树从右边看的从root到leaf的值。

We use an int depth to document the depth of we have travered. If depth is equal to size of res. We add the node’s value into res. It is kind like post order traversal. node->right-left order.

Code
/**
 * 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> res = new ArrayList<>();
        rightViewHelper(res, root, 0);
        return res;
    }
    
    private void rightViewHelper(List<Integer> res, TreeNode node, int depth){
        if (node == null){
            return;
        }
        if (depth == res.size()){
            res.add(node.val);
        }
        rightViewHelper(res, node.right, depth + 1);
        rightViewHelper(res, node.left, depth + 1);
    }
}

Time Complexity: O()
Space Complexity: O()


Review
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值