【LeetCode】199. 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].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

层次遍历,到每一层最后一个节点,即装入ret

每层最后一个节点的判断:

(1)队列为空

(2)下一个待遍历节点在下一层

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct Node
{
TreeNode* tnode;
int level; Node(TreeNode* t, int l): tnode(t), level(l) {}
}; class Solution {
public:
vector<int> rightSideView(TreeNode *root) {
vector<int> ret;
if(root == NULL)
return ret;
queue<Node*> q;
int curLevel = ;
Node* rootNode = new Node(root,);
q.push(rootNode); while(!q.empty())
{
Node* front = q.front();
q.pop(); if(q.empty() || q.front()->level > front->level)
//last node of current level
ret.push_back(front->tnode->val); if(front->tnode->left)
{
Node* leftNode = new Node(front->tnode->left, front->level+);
q.push(leftNode);
} if(front->tnode->right)
{
Node* rightNode = new Node(front->tnode->right, front->level+);
q.push(rightNode);
}
}
return ret;
}
};

【LeetCode】199. Binary Tree Right Side View

上一篇:Linux线程属性总结


下一篇:haproxy 规则匹配到了就停止,不会继续匹配下一个