###### tags: `leetcode` `easy` `Tree` `Depth-First Search` `Binary Tree` # [872. Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/description/) ## 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](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png) 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](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg) **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](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg) **Input**: root1 = [1,2,3], root2 = [1,3,2] **Output**: false ## Constraints: - The number of nodes in each tree will be in the range `[1, 200]`. - Both of the given trees will have values in the range `[0, 200]`. ## Code ```c= /** * 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)$| - $T_i, i\in \{1, 2\}$ : Number of nodes in root ## Result - Runtime : 0ms, 100% - Memory : 6.3 MB, 50%