[LeetCode] Binary Tree Right Side View
A simple application of level-order traversal. Just push the last node in each level into the result.
The code is as follows.
1 class Solution { 2 public: 3 vector<int> rightSideView(TreeNode* root) { 4 vector<int> right; 5 if (!root) return right; 6 queue<TreeNode*> toVisit; 7 toVisit.push(root); 8 while (!toVisit.empty()) { 9 TreeNode* rightNode = toVisit.back(); 10 right.push_back(rightNode -> val); 11 int num = toVisit.size(); 12 for (int i = 0; i < num; i++) { 13 TreeNode* node = toVisit.front(); 14 toVisit.pop(); 15 if (node -> left) toVisit.push(node -> left); 16 if (node -> right) toVisit.push(node -> right); 17 } 18 } 19 return right; 20 } 21 };
Well, the above code is of BFS. This problem can still be solved using DFS. The code is as follows. Play with it to see how it works :-)
1 class Solution { 2 public: 3 vector<int> rightSideView(TreeNode* root) { 4 vector<int> right; 5 if (!root) return right; 6 rightView(root, right, 0); 7 } 8 private: 9 void rightView(TreeNode* node, vector<int>& right, int level) { 10 if (!node) return; 11 if (level == right.size()) 12 right.push_back(node -> val); 13 rightView(node -> right, right, level + 1); 14 rightView(node -> left, right, level + 1); 15 } 16 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· 一文搞懂MCP协议与Function Call的区别
· 如何不购买域名在云服务器上搭建HTTPS服务