题目:
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
AC代码:
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<TreeNode*> q;
vector<int> vi;
q.push(root);
int height[100] = { 0 };
if (root) {
height[1] = 1;
}
else {
return vi;
}
int i = 1;
while (!q.empty()) {
if (--height[i] == 0) {
++i;
vi.push_back(q.front()->val);
if (q.front()->left) {
q.push(q.front()->left);
++height[i];
}
if (q.front()->right) {
q.push(q.front()->right);
++height[i];
}
q.pop();
}
else {
++i;
if (q.front()->left) {
q.push(q.front()->left);
++height[i];
}
if (q.front()->right) {
q.push(q.front()->right);
++height[i];
}
--i;
q.pop();
}
}
return vi;
}
};