From 51fbf503e2bb176f7b181b003bf4295a10d71a3f Mon Sep 17 00:00:00 2001 From: Vipul_Lakum Date: Tue, 4 Jun 2024 10:19:31 +0530 Subject: [PATCH 1/4] Same tree solution added --- .../lc-solutions/0100-0199/0100-same-tree.md | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 dsa-solutions/lc-solutions/0100-0199/0100-same-tree.md 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/) + +--- From 48809897dea4ba2fe24cfe21dbfc107f59a49d77 Mon Sep 17 00:00:00 2001 From: Vipul_Lakum Date: Tue, 4 Jun 2024 12:55:45 +0530 Subject: [PATCH 2/4] Symmetric tree solution added --- .../0100-0199/0101-symmetic-tree.md | 311 ++++++++++++++++++ 1 file changed, 311 insertions(+) create mode 100644 dsa-solutions/lc-solutions/0100-0199/0101-symmetic-tree.md diff --git a/dsa-solutions/lc-solutions/0100-0199/0101-symmetic-tree.md b/dsa-solutions/lc-solutions/0100-0199/0101-symmetic-tree.md new file mode 100644 index 000000000..75d64d10e --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0101-symmetic-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 From 47185aa58bec0f2633d8377538d179c979b58ac2 Mon Sep 17 00:00:00 2001 From: Vipul_Lakum Date: Tue, 4 Jun 2024 12:56:25 +0530 Subject: [PATCH 3/4] Symmetric tree solution added --- .../0100-0199/{0101-symmetic-tree.md => 0101-symmetric-tree.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename dsa-solutions/lc-solutions/0100-0199/{0101-symmetic-tree.md => 0101-symmetric-tree.md} (100%) diff --git a/dsa-solutions/lc-solutions/0100-0199/0101-symmetic-tree.md b/dsa-solutions/lc-solutions/0100-0199/0101-symmetric-tree.md similarity index 100% rename from dsa-solutions/lc-solutions/0100-0199/0101-symmetic-tree.md rename to dsa-solutions/lc-solutions/0100-0199/0101-symmetric-tree.md From 31674f1b5b34db382b812106f9403d112fa10543 Mon Sep 17 00:00:00 2001 From: Vipul_Lakum Date: Tue, 4 Jun 2024 13:37:34 +0530 Subject: [PATCH 4/4] Maximum Depth Of BInary Tree solution added --- .../0104-maximum-depth-of-binary-tree.md | 223 ++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 dsa-solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md diff --git a/dsa-solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md b/dsa-solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md new file mode 100644 index 000000000..331604352 --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md @@ -0,0 +1,223 @@ +--- +id: max-depth-binary-tree +title: Maximum Depth of Binary Tree Solution +sidebar_label: 0104 Maximum Depth of Binary Tree +tags: + - Binary Tree + - Depth-First Search + - Breadth-First Search + - Recursion + - LeetCode + - C++ + - Java + - Python +description: "This is a solution to the Maximum Depth of Binary Tree problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return its maximum depth. + +A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. + +### Examples + +**Example 1:** + +![Input Tree](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg) + +``` +Input: root = [3,9,20,null,null,15,7] +Output: 3 +``` + +**Example 2:** + +``` +Input: root = [1,null,2] +Output: 2 +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 104]`. +- `-100 <= Node.val <= 100` + +## Solution for Maximum Depth of Binary Tree Problem + + + + + +### Recursive (DFS) Approach + +#### Intuition + +To find the maximum depth of a binary tree, we can use a depth-first search (DFS) approach. We recursively find the maximum depth of the left and right subtrees and return the maximum of the two depths plus one (to account for the current level). + +#### Approach + +1. Implement a recursive function `maxDepth(root)` that returns the maximum depth of the binary tree rooted at `root`. +2. If the root is `null`, return 0. +3. Recursively find the maximum depth of the left and right subtrees. +4. Return the maximum of the left and right subtree depths plus one. + +#### Code in Different Languages + + + + + ```java + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + int maxLeft = maxDepth(root.left); + int maxRight = maxDepth(root.right); + return Math.max(maxLeft, maxRight) + 1; + } + ``` + + + + + ```python + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + maxLeft = self.maxDepth(root.left) + maxRight = self.maxDepth(root.right) + return max(maxLeft, maxRight) + 1 + ``` + + + + + ```cpp + int maxDepth(TreeNode* root) { + if (!root) + return 0; + int maxLeft = maxDepth(root->left); + int maxRight = maxDepth(root->right); + return max(maxLeft, maxRight) + 1; + } + ``` + + + + +#### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of nodes in the tree. We visit each node once. +- **Space complexity**: O(h), where h is the height of the tree. The space used by the recursive call stack is proportional to the height of the tree. + + + + +### Breadth-First Search (BFS) Approach + +#### Intuition + +Another approach to find the maximum depth of a binary tree is to use breadth-first search (BFS). We start from the root node and traverse the tree level by level, incrementing the depth at each level until we reach the deepest leaf node. + +#### Approach + +1. Initialize a queue and push the root node into it. +2. Initialize a variable `depth` to store the maximum depth, initially set to 0. +3. Perform BFS traversal: + - Increment `depth` for each level visited. + - Push all the children of the current level into the queue. +4. Return `depth` after traversing all levels. + +#### Code in Different Languages + + + + + ```java + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + + int depth = 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + ++depth; + int levelSize = queue.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode node = queue.poll(); + if (node.left != null) + queue.offer(node.left); + if (node.right != null) + queue.offer(node.right); + } + } + return depth; + } + ``` + + + + + ```python + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + + depth = 0 + queue = [root] + while queue: + depth += 1 + for _ in range(len(queue)): + node = queue.pop(0) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth + ``` + + + + + ```cpp + int maxDepth(TreeNode *root) { + if (root == NULL) + return 0; + + int depth = 0; + queue q; + q.push(root); + while (!q.empty()) { + ++depth; + int levelSize = q.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode *node = q.front(); + q.pop(); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + } + return depth; + } + ``` + + + + +#### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of nodes in the tree. We visit each node once. +- **Space complexity**: O(w), where w is the maximum width of the tree (i.e., the number of nodes at the maximum level). In the worst case, the maximum width could be n/2 in a complete binary tree, so the space complexity is O(n). + + + + +## References + +- **LeetCode Problem**: [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) +--- \ No newline at end of file