1. 程式人生 > >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]

.

/**
 * 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:

//按層遍歷BFS,從左到右,然後將最右邊的放入
    vector<int> rightSideView(TreeNode* root) {
        
        vector<int> ans;
        if(root==NULL)
            return ans;
        queue<TreeNode *>q;
        int kk;
        TreeNode *cur;
        q.push(root);
        while(!q.empty())
        {
            kk=q.size();
            for(int i=0;i<kk;i++)
            {
                cur=q.front();
                q.pop();
                if(cur->left)
                    q.push(cur->left);
                if(cur->right)
                    q.push(cur->right);
            }
            ans.push_back(cur->val);//插入最右邊的值
        }
        return ans;
    }
};