LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode easy Tree Depth-First Search Binary Tree

872. Leaf-Similar Trees

Description

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

Tree

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Examples

Example 1:

Leaf_Similar_1 Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true

Example 2:

Leaf_Similar_2 Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false

Constraints:

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
typedef struct TreeNode* TNODE;
typedef struct leafString {
    int val;
    struct leafString* next;
} LSTR;

void leafChecker(TNODE root, LSTR** lstr) {
    if (!root->left && !root->right) {
        // Create new node
        LSTR* newNode = (LSTR*)malloc(sizeof(LSTR));
        newNode->val = root->val;
        newNode->next = NULL;
        // Get the pointer of the last node
        LSTR *pre = NULL, *tmp = *lstr;
        while (tmp != NULL) {
            pre = tmp;
            tmp = tmp->next;
        }
        // Append new node
        if (pre)
            pre->next = newNode;
        else
            *lstr = newNode;
        return;
    }
    // If child of tree is not null
    if (root->left)
        leafChecker(root->left, lstr);
    if (root->right)
        leafChecker(root->right, lstr);
    return;
}

bool leafSimilar(struct TreeNode* root1, struct TreeNode* root2) {
    // If only one tree is empty, return false
    if ((!root1 && root2) || (root1 && !root2))
        return false;
    LSTR *lstr1 = NULL, *lstr2 = NULL;
    // In-order DFS search
    // Using address of pointer for null pointer assignment
    leafChecker(root1, &lstr1);
    leafChecker(root2, &lstr2);
    // Comparing leaf list
    while (lstr1 && lstr2) {
        if (lstr1->val != lstr2->val)
            return false;
        lstr1 = lstr1->next;
        lstr2 = lstr2->next;
    }
    if (lstr1 || lstr2)
        return false;
    return true;
}

Complexity

|Space |Time | |- |- | |$O(T_1 + T_2)$|$O(T_1 + T_2)$|

Result