您的位置:首页 > 其它

Binary Tree Right Side View 从左边视角输出二叉树的值

2015-06-01 17:43 113 查看


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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: