diff --git a/build_with_postorder_inorder.py b/build_with_postorder_inorder.py new file mode 100644 index 00000000..e74ae560 --- /dev/null +++ b/build_with_postorder_inorder.py @@ -0,0 +1,37 @@ +# Time Complexity: O(n) +# Space Complexity: O(n) +# Did this code successfully run on Leetcode : Yes + +# 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] + """ + hmap={} + self.rootindex=len(postorder)-1 + for i in range(len(inorder)): + hmap[inorder[i]]=i + + def helper(in_st,in_end): + if (in_st>in_end): + return None + + rootval=postorder[self.rootindex] + in_root_idx=hmap[rootval] + root = TreeNode(rootval) + self.rootindex-=1 + root.right = helper(in_root_idx+1,in_end) + root.left = helper(in_st,in_root_idx-1) + + return root + + + return helper(0,len(postorder)-1) \ No newline at end of file diff --git a/sum_root_to_leaf.py b/sum_root_to_leaf.py new file mode 100644 index 00000000..dc72a7d8 --- /dev/null +++ b/sum_root_to_leaf.py @@ -0,0 +1,30 @@ +# // Time Complexity : O(n) +# // Space Complexity : O(h) where h is the height of the tree, for recursive stack space +# // Did this code successfully run on Leetcode : Yes + +# 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 + """ + self.res=0 + + def helper(root,cur): + if root == None: return + cur=cur*10 + root.val + if root.left==None and root.right==None: + self.res+=cur + return + helper(root.left,cur) + helper(root.right,cur) + + helper(root,0) + + return self.res