【Binary Tree Right Side View 】cpp

题目:

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.

代码:

/**
 * 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;
            queue<TreeNode*> curr;
            queue<TreeNode*> next;
            if (root) { curr.push(root); ret.push_back(root->val); }
            while ( !curr.empty() )
            {
                while ( !curr.empty() )
                {
                    TreeNode* tmp = curr.front();
                    curr.pop();
                    if ( tmp->left ) next.push(tmp->left);
                    if ( tmp->right ) next.push(tmp->right);
                }
                if (!next.empty()) ret.push_back(next.back()->val);
                swap(next,curr);
            }
            return ret; 
    }
};

tips:

BFS算法,level order traversal binary tree

每次保留每一个level的最右一个元素的值。

原文地址:https://www.cnblogs.com/xbf9xbf/p/4646305.html