码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Right Side View

时间:2015-12-17 19:05:29      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

Binary Tree Right Side View

Total Accepted: 28755 Total Submissions: 92186 Difficulty: Medium

 

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].

 
/**
 * 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(TreeNode* root,vector<int>& res,int& res_size,int depth){
        if(!root) return ;
        if(depth==res_size){
            res_size++;
            res.push_back(root->val);
        }
        dfs(root->right,res,res_size,depth+1);
        dfs(root->left,res,res_size,depth+1);
    }
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        int res_size =0;
        dfs(root,res,res_size,0);
        return res;
    }
};

Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5054930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!