Binary Tree Right Side View

来源:互联网 发布:宏晶单片机烧录软件 编辑:程序博客网 时间:2024/06/02 03:47

题目:

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

看到这道题就想到了广度优先遍历,使用队列实现

不过中间出现了一个问题,就是怎么该标识每一层的结束,当时想到用二个队列,看了别人的代码后,才发现用size即可。。。

/** * 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*> q;        if(root!=NULL) q.push(root);        while(!q.empty()){            int k=q.size();            for(int i=0;i<k;++i)            {                TreeNode* tmp=q.front();q.pop();                if(i==k-1) ret.push_back(tmp->val);                if(tmp->left!=NULL) q.push(tmp->left);                if(tmp->right!=NULL) q.push(tmp->right);            }        }        return ret;    }};


0 0
原创粉丝点击