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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     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) {
        vector<int> ret;
        if(!root) return ret;
        queue<TreeNode*> q;
        TreeNode* nextStart = NULL;
        q.push(root);
        while(!q.empty()){
            TreeNode* cur = q.front();
            q.pop();
            if(!nextStart || nextStart == cur){
                nextStart = cur->left ? cur->left : cur->right; 
            }
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
            
            if(q.empty() || (!q.empty() && nextStart == q.front())){
                ret.push_back(cur->val);
            }
                
        }
        return ret;
    }
};

 

posted @ 2018-08-10 00:43  妖域大都督  阅读(116)  评论(0编辑  收藏  举报