leetcode 199. Binary Tree Right Side View

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 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) {
        queue<TreeNode*> q;
        vector<int> v;
        if (root == nullptr) return v;
        q.push(root);
        while(!q.empty()) {
            int x = q.size();
            int tmp;
            for (int i = 0; i < x; ++i) {
                TreeNode* u = q.front();q.pop();
                if (u->left != nullptr) q.push(u->left);
                if (u->right != nullptr) q.push(u->right);
                tmp = u->val;
            }
            v.push_back(tmp);
        }
        return v;
    }
};
posted on 2017-10-11 10:41  Beserious  阅读(100)  评论(0编辑  收藏  举报