872. Leaf-Similar Trees (C语言,递归)

题目:https://leetcode.com/problems/leaf-similar-trees/description/

比较2个BST树的叶子节点是否从左往右一致相同。

思路:前序遍历递归,当为叶子结点时赋值给数组。

注意点:1.遍历时的传参,传了一个数组及其未来长度的地址(有了长度,意味着下标值也就有了)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
void findLeaf(struct TreeNode *root, int *arr, int *ct) {
    if (!root) {
        return;
    } 
    if(!(root->left) && !(root->right)) {
        arr[*ct] = root->val;
        (*ct)++;
        printf("root->val=%d, *ct=%d\n", root->val, *ct);
    }
    findLeaf(root->left, arr, ct);
    findLeaf(root->right, arr, ct);
}

bool leafSimilar(struct TreeNode* root1, struct TreeNode* root2) {
    int ret1[64], ret2[64]; //2^(n+1) < 100 => n<6 => 第n层最多节点数为: 2^n, 得出2^n <64.
    int len1 = 0, len2 = 0;
    
    findLeaf(root1, ret1, &len1);
    findLeaf(root2, ret2, &len2);

    printf("len1=%d,len2=%d\n", len1, len2);
    if (len1 != len2) {
        return false;
    }
    int i;
    for (i = 0; i < len1; i++) {
        if (ret1[i] != ret2[i]) {
            return false;
        }            
    }
    return true;
}

Leaf-Similar Trees

Submission Detail

36 / 36 test cases passed.

Status: 

Accepted

Runtime: 0 ms

Submitted: 9 minutes ago


你可能感兴趣的:(Coding)