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].

解题思路:

题目中说的添加从右边看到的数并不是只添加右分支的数,当左分支的层数比右边大的时候也有可能被添加。

所以若是用递归来解题的话,我们需要用一个数来记录节点的层数,用一个数组来储存数字,只有当层数大于数组的个数(也就是添加过的数字最深层数),数字才能被添加。

然后我们做深度搜索,先从右边一条路探到黑,不行再换左边,一直递归遍历整个二叉树。以节点为空作为返回条件。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void view(TreeNode* root, int level, vector<int> &nums){
13         if(!root)
14         //最底层的返回条件
15             return;
16         if(level>nums.size())
17         //添加条件
18             nums.push_back(root->val);
19         view(root->right, level+1, nums);  //右边一条路探到黑
20         view(root->left, level+1, nums);   //再探左边
21         //中间节点两边搜完自动返回
22     }
23     vector<int> rightSideView(TreeNode* root) {
24         vector<int> ret;
25         view(root, 1, ret);
26         return ret;
27     }
28 };

 

转载于:https://www.cnblogs.com/sakuya0000/p/8689965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值