Binary Tree Right Side View

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

 

 

 hint: 使用层次遍历,并获取每层元素的内容,最后取每层最后的元素
/**
 * 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:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        if (root == NULL) {
            return ans;
        }
        
        vector<vector<int> > nums;
        vector<int> level_nums;
        queue<TreeNode*> qt;
        qt.push(root);
        qt.push(NULL);
        while (!qt.empty()) {
            TreeNode* cur = qt.front();
            qt.pop();
            
            if (cur == NULL) {
                nums.push_back(level_nums);
                level_nums.clear();
                if (!qt.empty()) {
                    qt.push(NULL);
                }
                continue;
            }
            
            level_nums.push_back(cur->val);
            if (cur->left) {
                qt.push(cur->left);
            }
            if (cur->right) {
                qt.push(cur->right);
            }
        }
        
        for (int i = 0; i < nums.size(); ++i) {
            ans.push_back(nums[i].back());
        }
        
        return ans;
    }
};

 

posted on 2016-02-21 16:54  bug睡的略爽  阅读(170)  评论(0编辑  收藏  举报

导航