LeetCode 199
Binary Tree Right Side View
Problem Description:
这道题目给出一棵二叉树,输入从右侧看树得到的结点值。
具体的题目信息:
https://leetcode.com/problems/binary-tree-right-side-view/description/- Example:
- Solution:
- 解题思路:可以通过层次遍历输出每一层最后一个结点值。
- 编程实现:
/**
* 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> result;
if (root == NULL) return result;
TreeNode* node[3000];
int front = -1, rear = -1;
int last = 0;
node[++rear] = root;
while(front<rear) {
TreeNode* p = node[++front];
if (p->left)
node[++rear] = p->left;
if (p->right)
node[++rear] = p->right;
if (front == last) {
result.push_back(p->val);
last = rear;
}
}
return result;
}
};