前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Leetcode 199 Binary Tree Right Side View

Leetcode 199 Binary Tree Right Side View

作者头像
triplebee
发布2018-01-12 14:46:46
发布2018-01-12 14:46:46
46300
代码可运行
举报
运行总次数:0
代码可运行

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,

代码语言:javascript
代码运行次数:0
运行
复制
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].

返回一棵二叉树从右边看得到的数。

本质是求二叉树每一层的最右边的一个元素,层序遍历?那样太复杂了。

遍历的时候记录深度,当返回数组的大小等于深度时,说明遍历到这一层时还没有找到最右边的数字,

因为我们是右子树优先遍历的,所以可以把当前值加入到结果中。

代码语言:javascript
代码运行次数:0
运行
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(vector<int> &res, TreeNode* root, int dep)
    {
        if(!root) return ;
        if(dep == res.size()) res.push_back(root->val);
        if(root->right) dfs(res, root->right, dep + 1);
        if(root->left) dfs(res, root->left, dep + 1);
    }
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res, flag;
        dfs(res, root, 0);
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-03-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档