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

[LeetCode]199.Binary Tree Right Side View

时间:2015-04-05 22:00:55      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:leetcode   经典面试题   

题目

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

思路

层次遍历

代码

    /*-------------------------------------------------------------------
    *   日期:2014-04-05
    *   作者:SJF0115
    *   题目: 199.Binary Tree Right Side View
    *   来源:https://leetcode.com/problems/binary-tree-right-side-view/
    *   结果:AC
    *   来源:LeetCode
    *   总结:
    --------------------------------------------------------------------*/
    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;

    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> result;
            if(root == nullptr){
                return result;
            }//if
            queue<TreeNode*> cur;
            queue<TreeNode*> next;
            cur.push(root);
            result.push_back(root->val);
            TreeNode *node,*pre;
            // 层次遍历
            while(!cur.empty()){
                pre = nullptr;
                while(!cur.empty()){
                    node = cur.front();
                    cur.pop();
                    if(node->left){
                        next.push(node->left);
                        pre = node->left;
                    }//if
                    if(node->right){
                        next.push(node->right);
                        pre = node->right;
                    }//if
                }//while
                if(pre != nullptr){
                   result.push_back(pre->val);
                }//if
                swap(cur,next);
            }//while
            return result;
        }
    };

int main() {
    Solution solution;
    TreeNode *root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->right = new TreeNode(5);
    root->right->right = new TreeNode(4);
    vector<int> result = solution.rightSideView(root);
    for(int i = 0;i < result.size();++i){
        cout<<result[i]<<" ";
    }//for
    cout<<endl;
    return 0;
}

运行时间

技术分享

[LeetCode]199.Binary Tree Right Side View

标签:leetcode   经典面试题   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/44891111

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