LeetCode OJ入门初探-199. 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].

思路:重点就是找每一层的最右边节点,注意是按层找,故可以使用队列,每次把每个父节点的所有子节点按照从左到右的顺序加入。

 


int* rightSideView(struct TreeNode* root, int* returnSize) {
queueA;
queueB;
queueC;
A.push(root);
while(!A.empty())
{
struct TreeNode *temp;
while(!A.empty())
{
temp = A.front();
if(temp->left!=NULL)
B.push(temp->left);
if(temp->right!=NULL)
B.push(temp->right);
A.pop();
}
C.push(temp);

while(!B.empty())
{
temp = B.front();
B.pop();
A.push(temp);
}

}
int *returnum = (int *)malloc(sizeof(int)*C.size());
*returnSize = C.size();
int i = 0;
while(!C.empty())
{
struct TreeNode* temp;
temp = C.front();
C.pop();
returnum[i] = temp->val;
i++;
}
return returnum;
}

发表评论