|
| 1 | +# Day 25 |
| 2 | + |
| 3 | +## ⭐️ Count Complete Tree Nodes – 25.1 |
| 4 | +### 🔗 Problem |
| 5 | +[LeetCode #222 – Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) |
| 6 | + |
| 7 | +### 🧠 Core Idea |
| 8 | +A complete binary tree can be counted more efficiently than traversing all nodes by exploiting its structure. |
| 9 | +At each node, compute the height of the left and right subtrees. |
| 10 | +If they are equal, the left subtree is a perfect binary tree, so its size is 2^h - 1, and the count continues recursively on the right subtree. |
| 11 | +If they differ, then the right subtree is perfect, and recursion continues on the left subtree. |
| 12 | +This divide-and-conquer approach avoids traversing entire subtrees when they are guaranteed to be full. |
| 13 | + |
| 14 | +### 📊 Example |
| 15 | +Input: root = [1,2,3,4,5,6] |
| 16 | + |
| 17 | +Output: 6 -> The tree is complete with all nodes filled except possibly the last level. |
| 18 | + |
| 19 | +### ⏱️ Complexity |
| 20 | +- Time: O((log n)2) – Each level computes subtree heights in O(log n), repeated across log n levels |
| 21 | + |
| 22 | +- Space: O(log n) – Recursion stack equal to tree height |
| 23 | + |
| 24 | +👉 See full code in [count_complete_tree_nodes.py](https://github.com/lyushher/LeetCode-Python-Easy-DSA/blob/main/day-25/count_complete_tree_nodes.py) |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +## ⭐️ Leaf-Similar Trees – 25.2 |
| 29 | +### 🔗 Problem |
| 30 | +[LeetCode #872 – Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) |
| 31 | + |
| 32 | +### 🧠 Core Idea |
| 33 | +Two binary trees are leaf-similar if their leaf value sequences (from left to right) are identical. |
| 34 | +Perform DFS on each tree, collecting values only when visiting a leaf node (no children). After traversal, compare the two sequences. |
| 35 | +If they match, the trees are leaf-similar regardless of internal structure. |
| 36 | + |
| 37 | +### 📊 Example |
| 38 | +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] |
| 39 | + |
| 40 | +Output: true → Both have leaf sequence [6,7,4,9,8]. |
| 41 | + |
| 42 | +### ⏱️ Complexity |
| 43 | +- Time: O(n + m) – Each tree fully traversed once |
| 44 | + |
| 45 | +- Space: O(h1 + h2) – Recursion stack proportional to each tree’s height (plus leaf lists) |
| 46 | + |
| 47 | +👉 See full code in [leaf_similar_trees.py](https://github.com/lyushher/LeetCode-Python-Easy-DSA/blob/main/day-25/leaf_similar_trees.py) |
0 commit comments