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

LeetCode OJ:Binary Tree Right Side View

时间:2015-04-20 13:12:01      阅读:155      评论:0      收藏: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,

  1            <---
 /   2     3         <---
 \       5     4       <---

You should return [1, 3, 4].

思路:

右子树优先遍历,同时计算遍历过的层次,遍历完右子树后开始遍历左子树,若左子树的深度比右子树的深,则把左子树更深层次的节点也加入结果集里面

代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    void rightSideView(TreeNode *root, vector<int> &res, int n){
        if(!root) return; 
        ++n;
        if(n == res.size() + 1){
            res.push_back(root->val);   
        }
        rightSideView(root->right, res, n);
        rightSideView(root->left, res, n);
    }
public:
    vector<int> rightSideView(TreeNode *root) {
        vector<int> res;
        rightSideView(root, res, 0);
        return res;
    }
};

 

LeetCode OJ:Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/csuer/p/4441170.html

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