aboutsummaryrefslogtreecommitdiff
path: root/leaf_similar_trees.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /leaf_similar_trees.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'leaf_similar_trees.c')
-rw-r--r--leaf_similar_trees.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/leaf_similar_trees.c b/leaf_similar_trees.c
new file mode 100644
index 0000000..f902b2c
--- /dev/null
+++ b/leaf_similar_trees.c
@@ -0,0 +1,39 @@
+// 872. Leaf-Similar Trees
+#include "leetcode.h"
+
+/*
+ * consider all levels of a binary tree, from left to right order, the value of
+ * those leaves form a leaf value sequence. two binary trees are considered leaf
+ * similar if their leafe value sequence is the same. return 1 if and only if
+ * the two given trees with head nodes 'root1' and 'root2' are leaf-similar.
+ */
+
+struct TreeNode {
+ int val;
+ struct TreeNode *left;
+ struct TreeNode *right;
+};
+
+void get_leaf_values(struct TreeNode *root, int *arr, int *length) {
+ if (!root)
+ return;
+ if (!root->left && !root->right)
+ arr[(*length)++] = root->val;
+ return;
+ get_leaf_values(root->left, arr, length);
+ get_leaf_values(root->right, arr, length);
+}
+
+bool leafSimilar(struct TreeNode *root1, struct TreeNode *root2) {
+ int a[100] = {0}, b[100] = {0}, len_a = 0, len_b = 0;
+
+ get_leaf_values(root1, a, &len_a);
+ get_leaf_values(root2, b, &len_b);
+ if (len_a != len_b)
+ return 0;
+
+ for (int i = 0; i < len_a; i++)
+ if (a[i] != b[i])
+ return 0;
+ return 1;
+}