diff --git a/resources/binary-search-tree.md b/resources/binary-search-tree.md index 3f7e626..07d2707 100644 --- a/resources/binary-search-tree.md +++ b/resources/binary-search-tree.md @@ -12,12 +12,13 @@ ### General - [Introduction to Binary Search Trees](/src/com/problems/binarysearchtree/IntroductionToBinarySearchTree.java) - [Search in a Binary Search Tree](/src/com/problems/binarysearchtree/SearchInBinarySearchTree.java) +- [Minimum Distance Between BST Nodes](/src/com/problems/binarysearchtree/MinimumDistanceBetweenBSTNodes.java) - [Minimum element in BST](/src/com/problems/binarysearchtree/MinimumElementInBinarySearchTree.java) - [Maximum element in BST](/src/com/problems/binarysearchtree/MaximumElementInBinarySearchTree.java) - [Ceil in a Binary Search Tree](/src/com/problems/binarysearchtree/CeilInBinarySearchTree.java) - [Floor in a Binary Search Tree](/src/com/problems/binarysearchtree/FloorInBinarySearchTree.java) - [Convert Sorted Array to Binary Search Tree](/src/com/problems/binarysearchtree/ConvertSortedArrayToBinarySearchTree.java) -- [Insert a Given Node in Binary Search Tree](/src/com/problems/binarysearchtree/InsertNodeInBinarySearchTree.java) +- [Insert into a Binary Search Tree](/src/com/problems/binarysearchtree/InsertIntoABinarySearchTree.java) - [Delete a Node in Binary Search Tree](/src/com/problems/binarysearchtree/DeleteNodeInBinarySearchTree.java) - [Kth largest/smallest element in Binary Search Tree](/src/com/problems/binarysearchtree/KthSmallestLargestElementInBinaryTree.java) - [Validate Binary Search Tree](/src/com/problems/binarysearchtree/CheckIfTreeIsBinarySearchTree.java) diff --git a/resources/binary-tree.md b/resources/binary-tree.md index 7d7952f..c97379f 100644 --- a/resources/binary-tree.md +++ b/resources/binary-tree.md @@ -31,12 +31,18 @@ - [Second minimum value in the binary tree](/src/com/problems/binarytree/SecondMinimumValueInBinaryTree.java) - [Check if the Binary Tree is Balanced Binary Tree](/src/com/problems/binarytree/CheckIfTheBinaryTreeIsHeightBalanced.java) - [Diameter of a Binary Tree](/src/com/problems/binarytree/DiameterOfBinaryTree.java) +- [Path Sum](/src/com/problems/binarytree/PathSum.java) - [Path Sum II](/src/com/problems/binarytree/PathSum2.java) - [Maximum Path Sum in Binary Tree from any node to any node](/src/com/problems/binarytree/MaximumPathSumBinaryTreeFromAnyNodeToAnyNode.java) - [Maximum Path Sum in Binary Tree from leaf to leaf](/src/com/problems/binarytree/MaximumPathSumNodesBinaryTreeFromLeafToLeafNode.java) - [Check if two trees are identical](/src/com/problems/binarytree/CheckTwoTreesAreIdenticalOrNot.java) - [Invert/Flip Binary Tree (Create)](/src/com/problems/binarytree/InvertBinaryTree.java) - [Subtree of Another Tree](/src/com/problems/binarytree/SubtreeOfAnotherTree.java) +- [Merge Two Binary Trees](/src/com/problems/binarytree/MergeTwoBinaryTrees.java) +- [Range Sum of BST](/src/com/problems/binarytree/RangeSumOfBST.java) +- [Leaf-Similar Trees](/src/com/problems/binarytree/LeafSimilarTrees.java) +- [Evaluate Boolean Binary Tree](/src/com/problems/binarytree/EvaluateBooleanBinaryTree.java) + - [Top view of a Binary Tree](/src/com/problems/binarytree/TopViewOfBinaryTree.java) @@ -45,7 +51,7 @@ - [Right view of Binary Tree](/src/com/problems/binarytree/RightViewOfBinaryTree.java) - [Boundary Traversal of Binary Tree](/src/com/problems/binarytree/BoundaryTraversalInBinaryTree.java) -- [Symmetric Binary Tree](/src/com/problems/binarytree/CheckForSymmetricalBinaryTree.java) +- [Symmetric Tree](/src/com/problems/binarytree/SymmetricTree.java) - [Print Root to Node Path in a Binary Tree](/src/com/problems/binarytree/PrintRootToNodePath.java) - [Lowest Common Ancestor of a Binary Tree](/src/com/problems/binarytree/LowestCommonAncestorOfBinaryTree.java) - [Maximum Width of Binary Tree](/src/com/problems/binarytree/MaximumWidthOfBinaryTree.java) diff --git a/src/com/ds/binarytree/TNode.java b/src/com/ds/binarytree/TNode.java index 16c69f1..362ac03 100644 --- a/src/com/ds/binarytree/TNode.java +++ b/src/com/ds/binarytree/TNode.java @@ -5,20 +5,21 @@ public class TNode { public static final int NULL = Integer.MIN_VALUE; public int data; + public int val; public TNode left, right, next; public TNode(int data) { - this.data = data; + this.data = this.val = data; } public TNode(int val, TNode left, TNode right) { - this.data = val; + this.data = this.val = val; this.left = left; this.right = right; } public TNode data(int data) { - this.data = data; + this.data = this.val = data; return this; } @@ -66,6 +67,20 @@ public static TNode withNodes(int... nums) { } return nodes[0]; } + public static TNode withObjectNodes(Integer... nums) { + int n = nums.length; + if (n == 0) return null; + TNode[] nodes = new TNode[n]; + for (int i = 0; i < n; i++) + nodes[i] = (nums[i] != null) ? new TNode(nums[i]) : null; + for (int i = 0; i < n; i++) { + if (null == nodes[i]) continue; + int left = i * 2 + 1, right = i * 2 + 2; + nodes[i].left = left < n ? nodes[left] : null; + nodes[i].right = right < n ? nodes[right] : null; + } + return nodes[0]; + } public static TNode imbalancedBST(int n) { int[] nums = new int[n]; diff --git a/src/com/problems/binarysearchtree/ConvertSortedArrayToBinarySearchTree.java b/src/com/problems/binarysearchtree/ConvertSortedArrayToBinarySearchTree.java index 1aa3a3a..a361d05 100644 --- a/src/com/problems/binarysearchtree/ConvertSortedArrayToBinarySearchTree.java +++ b/src/com/problems/binarysearchtree/ConvertSortedArrayToBinarySearchTree.java @@ -6,8 +6,11 @@ /* * Problem link : * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ + * * Solution link : + * https://www.youtube.com/watch?v=0K0uCMYq5ng * + * https://neetcode.io/solutions/convert-sorted-array-to-binary-search-tree */ public class ConvertSortedArrayToBinarySearchTree { public static void main(String[] args) { diff --git a/src/com/problems/binarysearchtree/InsertNodeInBinarySearchTree.java b/src/com/problems/binarysearchtree/InsertIntoABinarySearchTree.java similarity index 59% rename from src/com/problems/binarysearchtree/InsertNodeInBinarySearchTree.java rename to src/com/problems/binarysearchtree/InsertIntoABinarySearchTree.java index 6ee7d1b..69119cd 100644 --- a/src/com/problems/binarysearchtree/InsertNodeInBinarySearchTree.java +++ b/src/com/problems/binarysearchtree/InsertIntoABinarySearchTree.java @@ -5,23 +5,26 @@ /* * Problem link : - * https://leetcode.com/problems/insert-into-a-binary-search-tree/ - * https://practice.geeksforgeeks.org/problems/insert-a-node-in-a-bst/1 - * https://www.codingninjas.com/studio/problems/insert-into-a-binary-search-tree_1279913 + * https://leetcode.com/problems/insert-into-a-binary-search-tree/description/ + * https://www.geeksforgeeks.org/problems/insert-a-node-in-a-bst/1 + * https://www.naukri.com/code360/problems/insert-into-a-binary-search-tree_1279913 * * Solution link : * https://www.youtube.com/watch?v=FiFiNvM29ps&list=PLgUwDviBIf0q8Hkd7bK2Bpryj2xVJk8Vk&index=44 + * https://www.youtube.com/watch?v=Cpg8f79luEA * * https://takeuforward.org/binary-search-tree/insert-a-given-node-in-binary-search-tree/ + * https://neetcode.io/solutions/insert-into-a-binary-search-tree + * */ -public class InsertNodeInBinarySearchTree { +public class InsertIntoABinarySearchTree { public static void main(String[] args) { type1(); type2(); } - // iterative way of adding nodes to the leaf + // as this is an iterative approach we need to have a track of the parent node as well private static void type2() { TNode root = TNode.withNodes(4, 2, 7, 1, 3); int val = 5; @@ -29,32 +32,28 @@ private static void type2() { PrintUtl.levelOrder(root); } - private static TNode insertIntoBST2(TNode root, int target) { - if (root == null) return new TNode(target); - TNode node = root; + private static TNode insertIntoBST2(TNode root, int val) { + if (root == null) return new TNode(val); + // iteratively going to the specific node and alsa updating the parent node + TNode parent = root, node = root; while (null != node) { - // we will go to the left if the target is lesser than the node - if (target < node.data) { - // if the left is null, then we will successfully place the node there - if (node.left == null) { - node.left = new TNode(target); - break; - } + parent = node; + if (val < node.val) { node = node.left; } else { - // we will go to the right if the target is greater than the node - // if the right is null, then we will successfully place the node there - if (node.right == null) { - node.right = new TNode(target); - break; - } node = node.right; } } + if (val < parent.val) parent.left = new TNode(val); + else parent.right = new TNode(val); return root; } + // recursive way of adding nodes to the leaf + // recursively traverse to the specific position + // each time it will either go to the left side if target < root-val + // or go to the right side if root-val < target private static void type1() { TNode root = TNode.withNodes(4, 2, 7, 1, 3); PrintUtl.levelOrder(root); diff --git a/src/com/problems/binarysearchtree/LowestCommonAncestorInBinarySearchTree.java b/src/com/problems/binarysearchtree/LowestCommonAncestorInBinarySearchTree.java index b1c399a..3de62f1 100644 --- a/src/com/problems/binarysearchtree/LowestCommonAncestorInBinarySearchTree.java +++ b/src/com/problems/binarysearchtree/LowestCommonAncestorInBinarySearchTree.java @@ -4,16 +4,25 @@ /* * Problem link : - * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ + * https://neetcode.io/problems/lowest-common-ancestor-in-binary-search-tree * https://www.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1 * * Solution link : * https://www.youtube.com/watch?v=cX_kPV_foZc&list=PLgUwDviBIf0q8Hkd7bK2Bpryj2xVJk8Vk&index=48 + * https://www.youtube.com/watch?v=gs2LMfuOR9k * * https://takeuforward.org/binary-search-tree/lca-in-binary-search-tree/ + * https://neetcode.io/solutions/lowest-common-ancestor-of-a-binary-search-tree + * */ public class LowestCommonAncestorInBinarySearchTree { + // todo Lowest Common Ancestor of a Binary Search Tree is quite easier than Lowest Common Ancestor of a Binary Tree + // in binary search tree we have left < root < right + // so if p and q both less than root so the common ancestor will be in the left + // if p and q both greater than root so common ancestor will be on the right + // the last condition is p and q are in opposite side, then the current node is then common ancestor public static void main(String[] args) { type1(); type2(); @@ -25,24 +34,23 @@ public static void main(String[] args) { // we will go left if root data is greater than both p and q. // we will go right if both p and q are bigger // while traversing anywhere if we find that p and q are in opposite side - // that node will be the common ancestor - // recursive ways + // that node will be the common ancestor recursive ways private static void type2() { TNode root = TNode.makeBST(15); TNode p = new TNode(7); TNode q = new TNode(15); - TNode node = lca1(root, p, q); + TNode node = lca2(root, p, q); System.out.println(node); } - private static TNode lca1(TNode root, TNode p, TNode q) { + private static TNode lca2(TNode root, TNode p, TNode q) { if (null == root) return null; if (root.data > p.data && root.data > q.data) // node is greater than both of them - return lca1(root.left, p, q); + return lca2(root.left, p, q); else if (root.data < p.data && root.data < q.data) // node data is lesser than both of them - return lca1(root.right, p, q); + return lca2(root.right, p, q); else // both p and q are in opposite side return root; @@ -58,20 +66,24 @@ private static void type1() { TNode root = TNode.makeBST(15); TNode p = new TNode(7); TNode q = new TNode(15); - TNode node = root; - while (null != node) { - // node is greater than both of them - if (node.data > p.data && node.data > q.data) - node = node.left; - // node data is lesser than both of them - else if (node.data < p.data && node.data < q.data) - node = node.right; + TNode ans = lca1(root, p, q); + System.out.println(ans); + } + + private static TNode lca1(TNode root, TNode p, TNode q) { + while (null != root) { + // root is greater than both of them + if (root.data > p.data && root.data > q.data) + root = root.left; + // root data is lesser than both of them + else if (root.data < p.data && root.data < q.data) + root = root.right; else // both p and q are in opposite side - break; + return root; } - System.out.println(node); + return null; } } diff --git a/src/com/problems/binarysearchtree/MinimumDistanceBetweenBSTNodes.java b/src/com/problems/binarysearchtree/MinimumDistanceBetweenBSTNodes.java new file mode 100644 index 0000000..cae6bed --- /dev/null +++ b/src/com/problems/binarysearchtree/MinimumDistanceBetweenBSTNodes.java @@ -0,0 +1,46 @@ +package com.problems.binarysearchtree; + +import com.ds.binarytree.TNode; + +/* + * problem links : + * https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ + * https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=joxx4hTYwcw + * + * https://neetcode.io/solutions/minimum-distance-between-bst-nodes + * */ +public class MinimumDistanceBetweenBSTNodes { + public static void main(String[] args) { + type1(); + } + + // if we do an inorder traversal we will get the sorted list + // and in a sorted list we will get the minimum difference only by checking num[i-1] and nums[i] + // so we will carry 2 variables prev and max + private static void type1() { + TNode root = TNode.withObjectNodes(1, 0, 48, null, null, 12, 49); + int ans = minDiffInBST(root); + System.out.println(ans); + } + + + static int prev = -1, min = Integer.MAX_VALUE; + + public static int minDiffInBST(TNode root) { + traverse(root); + return min; + } + + private static void traverse(TNode root) { + if (null == root) return; + traverse(root.left); + if (prev != -1) { + min = Math.min(min, (root.val - prev)); + } + prev = root.val; + traverse(root.right); + } +} diff --git a/src/com/problems/binarytree/EvaluateBooleanBinaryTree.java b/src/com/problems/binarytree/EvaluateBooleanBinaryTree.java new file mode 100644 index 0000000..421acb3 --- /dev/null +++ b/src/com/problems/binarytree/EvaluateBooleanBinaryTree.java @@ -0,0 +1,42 @@ +package com.problems.binarytree; + +import com.ds.binarytree.TNode; + +/* + * problem links : + * https://leetcode.com/problems/evaluate-boolean-binary-tree/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=9a_cP54jn8Q + * + * https://neetcode.io/solutions/evaluate-boolean-binary-tree + * */ +public class EvaluateBooleanBinaryTree { + public static void main(String[] args) { + type1(); + } + + private static void type1() { + TNode root = TNode.makeBST(2, 1, 3, TNode.NULL, TNode.NULL, 0, 1); + boolean ans = evaluateTree(root); + System.out.println(ans); + } + + public static boolean evaluateTree(TNode root) { + // if node is null then we will return true + if (null == root) return true; + // if it is leaf node then we will check if it is 1 or not + if (root.left == null && root.right == null) { + return (root.val == 1); + } + // we will collect the values from left and right + boolean left = evaluateTree(root.left); + boolean right = evaluateTree(root.right); + // if thw val is 2 then it is OR if the value is 3 then it is AND + if (root.val == 2) { + return left || right; + } else { + return left && right; + } + } +} diff --git a/src/com/problems/binarytree/LeafSimilarTrees.java b/src/com/problems/binarytree/LeafSimilarTrees.java new file mode 100644 index 0000000..90ce9af --- /dev/null +++ b/src/com/problems/binarytree/LeafSimilarTrees.java @@ -0,0 +1,47 @@ +package com.problems.binarytree; + +import com.ds.binarytree.TNode; + +import java.util.ArrayList; +import java.util.List; + +/* + * problem links : + * https://leetcode.com/problems/leaf-similar-trees/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=Nr8dbnL0_cM + * + * https://neetcode.io/solutions/leaf-similar-trees + * */ +public class LeafSimilarTrees { + public static void main(String[] args) { + type1(); + } + + private static void type1() { + TNode root1 = TNode.withObjectNodes(3, 5, 1, 6, 2, 9, 8, null, null, 7, 4); + TNode root2 = TNode.withObjectNodes(3, 5, 1, 6, 7, 4, 2, null, null, null, null, null, null, 9, 8); + + boolean ans = leafSimilar(root1, root2); + System.out.println(ans); + } + + + public static boolean leafSimilar(TNode root1, TNode root2) { + List list1 = traverse(root1, new ArrayList<>()); + List list2 = traverse(root2, new ArrayList<>()); + return list1.equals(list2); + } + + + private static List traverse(TNode root, List list) { + if (null == root) return list; + if (root.left == null && root.right == null) { + list.add(root.val); + } + traverse(root.left, list); + traverse(root.right, list); + return list; + } +} diff --git a/src/com/problems/binarytree/MergeTwoBinaryTrees.java b/src/com/problems/binarytree/MergeTwoBinaryTrees.java new file mode 100644 index 0000000..8eca7ee --- /dev/null +++ b/src/com/problems/binarytree/MergeTwoBinaryTrees.java @@ -0,0 +1,44 @@ +package com.problems.binarytree; + +import com.ds.binarytree.TNode; +import com.util.PrintUtl; + +/* + * + * problem links : + * https://leetcode.com/problems/merge-two-binary-trees/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=QHH6rIK3dDQ + * + * https://neetcode.io/solutions/merge-two-binary-trees + * */ +public class MergeTwoBinaryTrees { + public static void main(String[] args) { + type1(); + } + + // simple recursive approach + private static void type1() { + TNode root1 = TNode.withCount(10); + TNode root2 = TNode.withCount(5); + TNode root = mergeTrees(root1, root2); + PrintUtl.levelOrder(root); + } + + public static TNode mergeTrees(TNode root1, TNode root2) { + // if both of the root is null then we will return null + if (null == root1 && null == root2) + return null; + // if one of the root is null then we will return the other node + if (null == root1 || null == root2) + return (null == root1) ? root2 : root1; + + // at this point we will have both of the non-null nodes, + // and we will recursively call for the left and right subtree + TNode node = new TNode(root1.data + root2.data); + node.left = mergeTrees(root1.left, root2.left); + node.right = mergeTrees(root1.right, root2.right); + return node; + } +} diff --git a/src/com/problems/binarytree/PathSum.java b/src/com/problems/binarytree/PathSum.java new file mode 100644 index 0000000..dbe86b9 --- /dev/null +++ b/src/com/problems/binarytree/PathSum.java @@ -0,0 +1,38 @@ +package com.problems.binarytree; + +import com.ds.binarytree.TNode; + +/* + * Problem link : + * https://leetcode.com/problems/path-sum/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=LSKQyOz_P8I + * + * https://neetcode.io/solutions/path-sum + */ +public class PathSum { + public static void main(String[] args) { + type1(); + } + + // recursive approach + private static void type1() { + TNode root = TNode.withCount(4); + int targetSum = 7; + boolean ans = hasPathSum(root, targetSum); + System.out.println(ans); + } + + public static boolean hasPathSum(TNode root, int targetSum) { + // if the node is null then we will return false + if (root == null) return false; + // if the node is a leaf node then we will check if the target sum is equal to node value or not + if (root.left == null && root.right == null) { + return (targetSum == root.val); + } + // else we will check left subtree and right subtree + return hasPathSum(root.left, targetSum - root.val) + || hasPathSum(root.right, targetSum - root.val); + } +} diff --git a/src/com/problems/binarytree/PathSum2.java b/src/com/problems/binarytree/PathSum2.java index c77f33d..c774604 100644 --- a/src/com/problems/binarytree/PathSum2.java +++ b/src/com/problems/binarytree/PathSum2.java @@ -10,6 +10,7 @@ * https://leetcode.com/problems/path-sum-ii/description/ * * Solution link : + * */ public class PathSum2 { public static void main(String[] args) { diff --git a/src/com/problems/binarytree/RangeSumOfBST.java b/src/com/problems/binarytree/RangeSumOfBST.java new file mode 100644 index 0000000..d84ac2d --- /dev/null +++ b/src/com/problems/binarytree/RangeSumOfBST.java @@ -0,0 +1,70 @@ +package com.problems.binarytree; + +import com.ds.binarytree.TNode; + +/* + * + * problem links : + * https://leetcode.com/problems/range-sum-of-bst/description/ + * + * Solution link : + * https://www.youtube.com/watch?v=uLVG45n4Sbg + * + * https://neetcode.io/solutions/range-sum-of-bst + * */ + + +public class RangeSumOfBST { + public static void main(String[] args) { + type1(); + type2(); + } + + // using binary search property + private static void type2() { + TNode root = TNode.withCount(25); + int low = 7, high = 15; + int ans = rangeSumBST2(root, low, high); + System.out.println(ans); + } + + public static int rangeSumBST2(TNode root, int low, int high) { + // if the root is null then we will return 0 + if (root == null) return 0; + int sum = 0; + // if the root val is in the range then we will add to the sum + if (low <= root.val && root.val <= high) { + sum += root.val; + } + // rather blindly calling the function for left and right subtree we will check if the root is greater than val or not + // if it is then there might be some numbers in the left subtree + if (root.val > low) + sum += rangeSumBST1(root.left, low, high); + // similar condition on the right side + if (root.val < high) + sum += rangeSumBST1(root.right, low, high); + return sum; + } + + // brute force approach + private static void type1() { + TNode root = TNode.withCount(25); + int low = 7, high = 15; + int ans = rangeSumBST1(root, low, high); + System.out.println(ans); + } + + public static int rangeSumBST1(TNode root, int low, int high) { + // if the root is null then we will return 0 + if (root == null) return 0; + int sum = 0; + // if the root val is in the range then we will add to the sum + if (low <= root.val && root.val <= high) { + sum += root.val; + } + // now we will get the sum from left and the right + sum += rangeSumBST1(root.left, low, high); + sum += rangeSumBST1(root.right, low, high); + return sum; + } +} diff --git a/src/com/problems/binarytree/SubtreeOfAnotherTree.java b/src/com/problems/binarytree/SubtreeOfAnotherTree.java index 82730d7..0be6011 100644 --- a/src/com/problems/binarytree/SubtreeOfAnotherTree.java +++ b/src/com/problems/binarytree/SubtreeOfAnotherTree.java @@ -3,19 +3,23 @@ import com.ds.binarytree.TNode; /* - * * problem links : * https://leetcode.com/problems/subtree-of-another-tree/description/ + * https://neetcode.io/problems/subtree-of-a-binary-tree * * Solution link : + * https://www.youtube.com/watch?v=E36O5SWp-LE * * https://takeuforward.org/data-structure/reorder-list/ + * https://neetcode.io/solutions/subtree-of-another-tree * */ public class SubtreeOfAnotherTree { public static void main(String[] args) { type1(); } + + // this is the simple approach using dfs // we will dfs till we find the same value // once we find the same value we will check from this node if both of the tree is identical or not @@ -29,20 +33,20 @@ private static void type1() { public static boolean isSubtree(TNode root, TNode subRoot) { if (null == root) return false; // if both values are same, then we will check if both tree are identical - if (root.data == subRoot.data && isSameTree(root, subRoot)) return true; + if (root.data == subRoot.data && isSame(root, subRoot)) return true; // else we will go for left and right child return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); } - public static boolean isSameTree(TNode root, TNode subRoot) { + public static boolean isSame(TNode root1, TNode root2) { // if both are null means both are identical - if (null == root && null == subRoot) return true; + if (null == root1 && null == root2) return true; // if anyone of them is non-null then, it is not identical - if (null == root || null == subRoot) return false; + if (null == root1 || null == root2) return false; // then we will check if the values are same and its left and right child is also same or not - return (root.data == subRoot.data) - && isSameTree(root.left, subRoot.left) - && isSameTree(root.right, subRoot.right); + return (root1.data == root2.data) + && isSame(root1.left, root2.left) + && isSame(root1.right, root2.right); } } diff --git a/src/com/problems/binarytree/CheckForSymmetricalBinaryTree.java b/src/com/problems/binarytree/SymmetricTree.java similarity index 60% rename from src/com/problems/binarytree/CheckForSymmetricalBinaryTree.java rename to src/com/problems/binarytree/SymmetricTree.java index 89b0328..8a1d602 100644 --- a/src/com/problems/binarytree/CheckForSymmetricalBinaryTree.java +++ b/src/com/problems/binarytree/SymmetricTree.java @@ -5,20 +5,35 @@ /* * Problem link : * https://leetcode.com/problems/symmetric-tree/ - * https://www.codingninjas.com/codestudio/problems/630426 - * https://www.codingninjas.com/studio/problems/symmetric-tree_981177 + * https://www.naukri.com/code360/problems/630426 + * https://www.naukri.com/code360/problems/symmetric-tree_981177 * * Solution link : * https://www.youtube.com/watch?v=nKggNAiEpBE&list=PLgUwDviBIf0q8Hkd7bK2Bpryj2xVJk8Vk&index=26 + * https://www.youtube.com/watch?v=Mao9uzxwvmc * * https://takeuforward.org/data-structure/check-for-symmetrical-binary-tree/ + * https://neetcode.io/solutions/symmetric-tree */ -public class CheckForSymmetricalBinaryTree { +public class SymmetricTree { public static void main(String[] args) { type1(); } + // to check symmetry of a tree + // if we think of a center then that would be the root node + // so from the root node we will check its left subtree and right subtree + // lets say if the tree is like + /* + * 1 + * 2 2 + * 4 5 5 4 + * */ + // if we consider left subtree and right subtree different tree then from the diagram we can visualize that + // left.left should be equal to right.right + // and left.right should be equal to right.left + // we will create a recurrence relation from the conditions private static void type1() { TNode root = TNode.withNodes(1, 2, 2, 3, 4, 4, 3); boolean isSymmetric = isSymmetric(root); @@ -37,7 +52,7 @@ private static boolean isSymmetric(TNode root1, TNode root2) { if (null == root1 || null == root2) return false; // if both is non-null, then first we will check the values of the node // as we are checking the symmetric, so we will now check cris-cross - return root1.data == root2.data + return (root1.data == root2.data) && isSymmetric(root1.left, root2.right) && isSymmetric(root1.right, root2.left); } diff --git a/src/com/util/PrintUtl.java b/src/com/util/PrintUtl.java index 9868ea6..85a2a37 100644 --- a/src/com/util/PrintUtl.java +++ b/src/com/util/PrintUtl.java @@ -312,7 +312,4 @@ public static void printStrings(char[][] arr) { System.out.println(); } - public static void print2D(List list) { - - } }