Posts

Showing posts with the label leetcode

LeetCode | Hard | 1932 Merge BSTs to Create Single BST | Python Solution

  Approach Indentify your root tree from where merging will being . Now from remaining trees , apply helper function to merge. If final tree is valid BST then return tree else return None. Youtube Link :  https://www.youtube.com/watch?v=3QC5L5W0Lhk # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): is_merged = False def canMerge(self, trees): """ :type trees: List[TreeNode] :rtype: TreeNode """ if len(trees) == 1 : return trees[ 0 ] #Find List of Leaf Nodes all_leaves_node = set() for tree in trees : if tree.left : all_leaves_node.add(tree.left.val) if tree.right : all_leaves_node.add(tree.right.val) # Find start ...

LeetCode Problem 66 - Plus One - Algorithm and Java Solution

 Hi Friends, Today we are going to solve a leetcode problem number 66. Please feel free to read problem description from below link. https://leetcode.com/problems/plus-one/ In given problem , it states that you have a non-empty and non-negative array storing single digit value at each position and most significant bit is stored at head of list. Now we look at below example , when 1 is added to last digit 3 , it becomes 4 which would be simple to achieve. Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. But problem comes when last digit is 9 where you add 1 , it becomes 2 digit number = 10 which is not allowed in array. So in that you have keep 0 at unit place and use carry 1 to be added in next digit. For Example  Input: digits = [1,2,9] Output: [1,3,0] Explanation: The array represents the integer 130. Now in above example , 1 added to 9 is replaced with 0 and carry got added to 2 became 3. Corner Case: Everything works fine exc...