diff --git a/dsa-solutions/lc-solutions/0100-0199/0100-same-tree.md b/dsa-solutions/lc-solutions/0100-0199/0100-same-tree.md new file mode 100644 index 000000000..5d1e2abf3 --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0100-same-tree.md @@ -0,0 +1,143 @@ +--- +id: same-tree +title: Same Tree Solution +sidebar_label: 0100 Same Tree +tags: + - Binary Tree + - Recursion + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Same Tree problem on LeetCode." +--- + +## Problem Description + +Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. + +Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. + +### Examples + +**Example 1:** + +``` +Input: p = [1,2,3], q = [1,2,3] +Output: true +``` + +**Example 2:** + +``` +Input: p = [1,2], q = [1,null,2] +Output: false +``` + +**Example 3:** + +``` +Input: p = [1,2,1], q = [1,1,2] +Output: false +``` + +### Constraints + +- The number of nodes in both trees is in the range `[0, 100]`. +- `$-10^4 <=$ Node.val $<= 10^4$` + +## Solution for Same Tree Problem + +### Intuition + +The intuition behind the solution is to recursively check if two binary trees are identical. If both trees are empty (null), they are considered identical. If only one tree is empty or the values of the current nodes are different, the trees are not identical. Otherwise, we recursively check if the left and right subtrees of both trees are identical. + +### Approach + +1. Check the base case: if both trees are null, return true. +2. Check if only one tree is null or the values of the current nodes are different, return false. +3. Recursively check if the left subtrees of both trees are identical. +4. Recursively check if the right subtrees of both trees are identical. +5. Return the logical AND of the results from steps 3 and 4. + +#### Code in Different Languages + + + + + ```javascript + function isSameTree(p, q) { + if (p === null && q === null) { + return true; + } + if (p === null || q === null || p.val !== q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + ``` + + + + + + ```python + class Solution: + def isSameTree(self, p, q): + if p is None and q is None: + return True + if p is None or q is None or p.val != q.val: + return False + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) + ``` + + + + + ```java + class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } + if (p == null || q == null || p.val != q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + } + ``` + + + + + ```cpp + class Solution { + public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == nullptr && q == nullptr) { + return true; + } + if (p == nullptr || q == nullptr || p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: The time complexity of the solution is O(min(N,M)), where N and M are the number of nodes in the two trees, respectively. This is because we need to visit each node once in order to compare their values. +- **Space complexity**: The space complexity of the solution is O(min(H1,H2)), where H1 and H2 are the heights of the two trees, respectively. This is because the space used by the recursive stack is determined by the height of the smaller tree. + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/generate-parentheses/) +- **Solution Link:** [Generate Parantheses Solution on LeetCode](https://leetcode.com/problems/generate-parentheses/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + +--- diff --git a/dsa-solutions/lc-solutions/0100-0199/0101-symmetric-tree.md b/dsa-solutions/lc-solutions/0100-0199/0101-symmetric-tree.md new file mode 100644 index 000000000..75d64d10e --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0101-symmetric-tree.md @@ -0,0 +1,311 @@ +--- +id: symmetric-tree +title: Symmetric Tree Solution +sidebar_label: 0101 Symmetric Tree +tags: + - Binary Tree + - Recursion + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Symmetric Tree problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). + +### Examples + +**Example 1:** + +![LeetCode Problem - Symmetric Tree](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg) +``` +Input: root = [1,2,2,3,4,4,3] +Output: true +``` + +**Example 2:** + +![LeetCode Problem - Symmetric Tree](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg) + +``` +Input: root = [1,2,2,null,3,null,3] +Output: false +``` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `-100 <= Node.val <= 100` + +--- + +## Solution for Symmetric Tree Problem + +### Intuition And Approach + +To check if a binary tree is symmetric, we need to compare its left subtree and right subtree. We can define a recursive helper function that takes two nodes as input, one from the left subtree and one from the right subtree. The helper function returns true if both nodes are null, or if their values are equal and their subtrees are symmetric. + + + + +### Approach 1 : Recursive + +1. Define a recursive helper function `isMirror(node1, node2)` that returns true if both nodes are null or if their values are equal and their subtrees are symmetric. +2. Start the recursion from the root of the tree using `isMirror(root.left, root.right)`. +3. Return the result of the recursive check. + +#### Code in Different Languages + + + + + ```java + public boolean isSymmetric(TreeNode root) { + return root == null || isSymmetricHelp(root.left, root.right); + } + + private boolean isSymmetricHelp(TreeNode left, TreeNode right) { + if (left == null || right == null) + return left == right; + if (left.val != right.val) + return false; + return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left); + } + ``` + + + + + ```python + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + + def isSymmetricHelp(left, right): + if left is None or right is None: + return left == right + if left.val != right.val: + return False + return isSymmetricHelp(left.left, right.right) and isSymmetricHelp(left.right, right.left) + + return isSymmetricHelp(root.left, root.right) + ``` + + + + + ```cpp + bool isSymmetric(TreeNode* root) { + if (root == nullptr) { + return true; + } + return isSymmetricHelp(root->left, root->right); + } + + bool isSymmetricHelp(TreeNode* left, TreeNode* right) { + if (left == nullptr || right == nullptr) + return left == right; + if (left->val != right->val) + return false; + return isSymmetricHelp(left->left, right->right) && isSymmetricHelp(left->right, right->left); + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n) where n is the number of nodes in the binary tree. +- Space Complexity: O(h) where h is the height of the binary tree. + + + + +### Approach 2 : Non-Recursive (Stack-based) + +1. If the root is null, return true as an empty tree is symmetric. +2. Initialize a stack to store nodes for comparison. +3. If the root's left child is not null, check if the root's right child is also not null. If either is null while the other is not, return false. +4. Push both the left and right children of the root onto the stack. +5. While the stack is not empty: + - If the size of the stack is odd, return false as nodes should be in pairs. + - Pop two nodes from the stack. These nodes should be symmetric. + - Compare their values. If they are not equal, return false. + - For each popped pair of nodes, push their left and right children in the symmetric order onto the stack: + - Push the left child of the left node and the right child of the right node. + - Push the right child of the left node and the left child of the right node. + - If one node has a child while the other does not, return false. +6. If all nodes are processed without mismatch, return true as the tree is symmetric. + +#### Code in Different Languages + + + + + ```java + public boolean isSymmetric(TreeNode root) { + if (root == null) + return true; + + Stack stack = new Stack<>(); + TreeNode left, right; + if (root.left != null) { + if (root.right == null) + return false; + stack.push(root.left); + stack.push(root.right); + } else if (root.right != null) { + return false; + } + + while (!stack.empty()) { + if (stack.size() % 2 != 0) + return false; + right = stack.pop(); + left = stack.pop(); + if (right.val != left.val) + return false; + + if (left.left != null) { + if (right.right == null) + return false; + stack.push(left.left); + stack.push(right.right); + } else if (right.right != null) { + return false; + } + + if (left.right != null) { + if (right.left == null) + return false; + stack.push(left.right); + stack.push(right.left); + } else if (right.left != null) { + return false; + } + } + + return true; + } + ``` + + + + + ```python + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + + stack = [] + left, right = None, None + if root.left is not None: + if root.right is None: + return False + stack.append(root.left) + stack.append(root.right) + elif root.right is not None: + return False + + while stack: + if len(stack) % 2 != 0: + return False + right = stack.pop() + left = stack.pop() + if right.val != left.val: + return False + + if left.left is not None: + if right.right is None: + return False + stack.append(left.left) + stack.append(right.right) + elif right.right is not None: + return False + + if left.right is not None: + if right.left is None: + return False + stack.append(left.right) + stack.append(right.left) + elif right.left is not None: + return False + + return True + ``` + + + + + ```cpp + bool isSymmetric(TreeNode* root) { + if (root == nullptr) { + return true; + } + + stack stack; + TreeNode *left, *right; + if (root->left != nullptr) { + if (root->right == nullptr) + return false; + stack.push(root->left); + stack.push(root->right); + } else if (root->right != nullptr) { + return false; + } + + while (!stack.empty()) { + if (stack.size() % 2 != 0) + return false; + right = stack.top(); + stack.pop(); + left = stack.top(); + stack.pop(); + if (right->val != left->val) + return false; + + if (left->left != nullptr) { + if (right->right == nullptr) + return false; + stack.push(left->left); + stack.push(right->right); + } else if (right->right != nullptr) { + return false; + } + + if (left->right != nullptr) { + if (right->left == nullptr) + return false; + stack.push(left->right); + stack.push(right->left); + } else if (right->left != nullptr) { + return false; + } + } + + return true; + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n) where n is the number of nodes in the binary tree. +- Space Complexity: O(n) in the worst case due to the stack. + + + + +## References + +- **LeetCode Problem:** [Symmetric Tree Problem](https://leetcode.com/problems/symmetric-tree/) +- **Solution Link:** [Symmetric Tree Solution on LeetCode](https://leetcode.com/problems/symmetric-tree/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + +--- \ No newline at end of file