2015.4.17 06:04
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,
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].
You should return [1, 3, 4]
.
Solution:
Recursion can provide you with a short solution. So make it simple.
Accepted code:
1 // 1AC, easy with recursive 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 vector<int> rightSideView(TreeNode *root) { 14 vector<int> res; 15 if (root == nullptr) { 16 return res; 17 } 18 19 dfs(root, 1, res); 20 return res; 21 } 22 private: 23 void dfs(TreeNode *ptr, int dep, vector<int> &res) { 24 if (dep > res.size()) { 25 res.push_back(ptr->val); 26 } 27 28 if (ptr->right != nullptr) { 29 dfs(ptr->right, dep + 1, res); 30 } 31 if (ptr->left != nullptr) { 32 dfs(ptr->left, dep + 1, res); 33 } 34 } 35 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)