首页 > 学院 > 开发设计 > 正文

199. Binary Tree Right Side View

2019-11-06 07:47:49
字体:
来源:转载
供稿:网友

思路:遍历二叉树,先右后左,在第一次遍历到某一层的时候,记录该元素。

struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: void dfs(TreeNode* ptr, int depth, vector<int>& res) { if (ptr == NULL) { return; } if (depth >= res.size()) { res.push_back(ptr->val); } dfs(ptr->right, depth + 1, res); dfs(ptr->left, depth + 1, res); } vector<int> rightSideView(TreeNode* root) { vector<int> res; dfs(root, 0, res); return res; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表