【LeetCode】199. Binary Tree Right Side View

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

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

 

层次遍历,到每一层最后一个节点,即装入ret

每层最后一个节点的判断:

(1)队列为空

(2)下一个待遍历节点在下一层

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct Node
{
    TreeNode* tnode;
    int level;
    
    Node(TreeNode* t, int l): tnode(t), level(l) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode *root) {
        vector<int> ret;
        if(root == NULL)
            return ret;
        queue<Node*> q;
        int curLevel = 0;
        Node* rootNode = new Node(root,0);
        q.push(rootNode);
        
        while(!q.empty())
        {
            Node* front = q.front();
            q.pop();
            
            if(q.empty() || q.front()->level > front->level)
            //last node of current level
                ret.push_back(front->tnode->val);
            
            if(front->tnode->left)
            {
                Node* leftNode = new Node(front->tnode->left, front->level+1);
                q.push(leftNode);
            }
            
            if(front->tnode->right)
            {
                Node* rightNode = new Node(front->tnode->right, front->level+1);
                q.push(rightNode);
            }
        }
        return ret;
    }
};

你可能感兴趣的:(LeetCode)