【C语言刷LeetCode】199. 二叉树的右视图(M)

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

主要在这一句代码:array[new++] = root->val,每一行的最后一个节点,覆盖。

void preorder(struct TreeNode* root, int* array, int *line, int new) {
    if(root ==NULL) return;
    
    array[new++] = root->val;
    *line = (new > *line) ? new : *line;
    
    preorder(root->left, array, line, new);
    preorder(root->right, array, line, new);    
}

int* rightSideView(struct TreeNode* root, int* returnSize){
    int *array;
    int line = 0;
    int i;
    
    *returnSize = 0;
    array = (int *)malloc(sizeof(int) * 1024);
    memset(array, 0, sizeof(int) * 1024);
    
    if(root == NULL) {
        return 0;
    }
    
    preorder(root, array, &line, 0);
    *returnSize = line;
    
    return array;
}
发布了124 篇原创文章 · 获赞 17 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/jin615567975/article/details/104380176