这道题,我看了一个特别好的解法,而且可以不用深度优先搜索,由此想分享一下
题目链接:. - 力扣(LeetCode)
思路:先遍历左子树,把同一高度的值,放在一个数组里,在遍历右数组,将同一高度的值替换,
由此完成
下面举一个列子:
void test(struct TreeNode* root ,int height, int* Array , int* returnSize )
{
if( root == NULL )
{
return ;
}
if( height + 1 > *returnSize )//height为当前高度,*returnSize为当前已知最高高度
*returnSize = height + 1;
Array[height] = root->val;//主要是运用到height在同一高度上是不变的
test(root->left,height+1,Array,returnSize);
test(root->right,height+1,Array,returnSize);
return;
}
int* rightSideView(struct TreeNode* root, int* returnSize) {
int* Array = (int*)calloc(sizeof(int) , 1010 );//设置1010是为了防止对数组的越界
*returnSize = 0;
test(root,0,Array,returnSize);
return Array;
}