2020年5月24日
LeetCode 199. Binary Tree Right Side View
C++, LeetCode, 算法, 编程
0 Comments
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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
解析:从二叉树右侧角度查看二叉树,还是采用队列进行层次遍历二叉树,只不过输出队列尾端的数值,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int len = q.size();
result.push_back(q.back()->val);
for(int i =0 ; i < len; i++)
{
TreeNode *temp = q.front();
q.pop();
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
return result;
}
};