diff --git a/SumRootToLeafNumbers.py b/SumRootToLeafNumbers.py new file mode 100644 index 00000000..006872b0 --- /dev/null +++ b/SumRootToLeafNumbers.py @@ -0,0 +1,39 @@ +# 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): + def sumNumbers(self, root): + """ + :type root: Optional[TreeNode] + :rtype: int + """ + if not root: + return 0 + + self.ans = 0 + + def helper(root, total): + #if we hit a null node, nothing to process. + if not root: + return + + if not root.left and not root.right: + total = (total * 10) + root.val + #We are at the leaf node. Time to add total to the result. + self.ans += total + return + + curTotal = (total * 10) + root.val + + # Expand our search + helper(root.left, curTotal) + helper(root.right, curTotal) + + helper(root, 0) + return self.ans + + #TC: O(n) + #SC : O(h) \ No newline at end of file diff --git a/TreeFromPostorderInorder.py b/TreeFromPostorderInorder.py new file mode 100644 index 00000000..da2bfd95 --- /dev/null +++ b/TreeFromPostorderInorder.py @@ -0,0 +1,48 @@ +# 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): + def buildTree(self, inorder, postorder): + """ + :type inorder: List[int] + :type postorder: List[int] + :rtype: Optional[TreeNode] + """ + if not inorder or not postorder: + return None + + self.idxMap = dict() + + for i in range(len(inorder)): + self.idxMap[inorder[i]] = i + + #postorder array. tree root will be the last. + self.treeRootIdx = len(postorder) - 1 + + def helper(postorder, start, end): + if start > end: + return None + + rootVal = postorder[self.treeRootIdx] + self.treeRootIdx -= 1 + rootIdx = self.idxMap[rootVal] + + root = TreeNode(rootVal) + + # Populate right and left children recursively. + # why right? because we are using postorder array + # to determine the next root. + root.right = helper(postorder, rootIdx + 1, end) + + root.left = helper(postorder, start, rootIdx - 1) + + return root + + return helper(postorder, 0 , len(inorder)-1) + + +#TC : O(n) +#SC : O(n) \ No newline at end of file