[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 };
复制代码

 

posted @   jianchao-li  阅读(235)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· 一文搞懂MCP协议与Function Call的区别
· 如何不购买域名在云服务器上搭建HTTPS服务
点击右上角即可分享
微信分享提示