Created
October 4, 2018 03:03
-
-
Save Henryhehe/3426aed06995cdfa4beed5fc5e577bb7 to your computer and use it in GitHub Desktop.
Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Same Tree | |
| class Solution: | |
| def isSameTree(self, p, q): | |
| """ | |
| :type p: TreeNode | |
| :type q: TreeNode | |
| :rtype: bool | |
| """ | |
| result = self.isSame(p,q) | |
| return result | |
| def isSame(self, p ,q): | |
| if p==None and q==None: | |
| return True | |
| if (p!=None and q==None) or (p==None and q!=None) or (p.val!=q.val): | |
| return False | |
| return self.isSame(p.left,q.left) and self.isSame(p.right,q.right) | |
| #Merge Two binary Tree | |
| class Solution: | |
| def mergeTrees(self, t1, t2): | |
| """ | |
| :type t1: TreeNode | |
| :type t2: TreeNode | |
| :rtype: TreeNode | |
| """ | |
| return self.preOrderSum(t1,t2) | |
| def preOrderSum(self,t1,t2): | |
| if t1 == None and t2 ==None: | |
| return None | |
| elif t1!=None and t2==None: | |
| return t1 | |
| elif t1==None and t2!=None: | |
| return t2 | |
| t1.val += t2.val | |
| t1.left = self.preOrderSum(t1.left,t2.left) | |
| t1.right = self.preOrderSum(t1.right,t2.right) | |
| return t1 | |
| # Validate binary Tree | |
| class Solution: | |
| def isValidBST(self, root): | |
| """ | |
| :type root: TreeNode | |
| :rtype: bool | |
| """ | |
| va = self.valid(root, -9999999999999999,999999999999999999) | |
| return va | |
| def valid(self,root,minValue,maxValue): | |
| #base case | |
| if root == None: | |
| return True | |
| if root.val > minValue and root.val <maxValue and self.valid(root.left,minValue,root.val) and self.valid(root.right,root.val,maxValue): | |
| return True | |
| else: | |
| return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment