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

[LeetCode]Binary Tree Right Side View

时间:2015-04-09 22:02:36      阅读:117      评论: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 {
public:
   vector<int> rightSideView(TreeNode *root) {
        vector<int> ans;
        if (!root)
            return ans;
        queue<TreeNode*> q;
        q.push(root);
        int count = 1;
        int num = 0;
        while (!q.empty()){
            root = q.front();
            q.pop();
            count--;
            if (root->left){
                q.push(root->left);
                num++;
            }
            if (root->right){
                q.push(root->right);
                num++;
            }
            if (count == 0){
                ans.push_back(root->val);
                count = num;
                num = 0;
            }
        }
        return ans;
    }
};

[LeetCode]Binary Tree Right Side View

标签:

原文地址:http://blog.csdn.net/kaitankedemao/article/details/44964509

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