您的位置:首页 > 其它

[LeetCode]Binary Tree Right Side View

2015-04-09 19:52 316 查看
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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: