199. Binary Tree Right Side View

来源:互联网 发布:wind万德数据库官网 编辑:程序博客网 时间:2024/05/20 21:21

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

思路:层次遍历,遍历的时候用队列把右边的先放进去,把每层front的值放到结果中就可以了。

class Solution {public:    vector<int> rightSideView(TreeNode* root) {       vector<int> result;if(root == NULL) return result;queue<TreeNode*> layer;layer.push(root);result.push_back(root->val);while(!layer.empty()){int currentSize = layer.size();for(int i = 0; i < currentSize; i++){TreeNode* node = layer.front();layer.pop();if(node->right!=NULL) layer.push(node->right);if(node->left!=NULL) layer.push(node->left);}if(!layer.empty()) result.push_back(layer.front()->val);}return result;    }};


0 0
原创粉丝点击