您的位置:首页 > 其它

LeetCode(199) Binary Tree Right Side View

2015-08-11 22:28 393 查看
map算法

[code]/**
 * 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 preorder(TreeNode *root, int depth, map<int, int> &map1) {

        map1[depth] = root->val;

        if(root->left != NULL)

            preorder(root->left, depth + 1, map1);

        if(root->right != NULL)

            preorder(root->right, depth + 1, map1);

    }
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result;

        if(root == NULL)

            return result;

        map<int, int> map1;
        preorder(root, 0, map1);

        map<int, int>::iterator iter = map1.begin();

        for(; iter != map1.end(); iter++) 

            result.push_back(iter->second);

        return result;

    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: