same_tree
1from utils import TreeNode 2from typing import Optional 3 4 5# @leet start 6class Solution: 7 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 8 """ 9 We can recursively define the same tree as follows: 10 1. if the two tree nodes are null 11 2. if the two tree nodes are non-null and they have the same value. 12 We then apply the same rule to all nodes in both trees. 13 """ 14 if not p and not q: 15 return True 16 if not p or not q: 17 return False 18 return ( 19 p.val == q.val 20 and self.isSameTree(p.left, q.left) 21 and self.isSameTree(p.right, q.right) 22 ) 23 24 25# @leet end 26 27 28def test(): 29 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 9 """ 10 We can recursively define the same tree as follows: 11 1. if the two tree nodes are null 12 2. if the two tree nodes are non-null and they have the same value. 13 We then apply the same rule to all nodes in both trees. 14 """ 15 if not p and not q: 16 return True 17 if not p or not q: 18 return False 19 return ( 20 p.val == q.val 21 and self.isSameTree(p.left, q.left) 22 and self.isSameTree(p.right, q.right) 23 )
8 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 9 """ 10 We can recursively define the same tree as follows: 11 1. if the two tree nodes are null 12 2. if the two tree nodes are non-null and they have the same value. 13 We then apply the same rule to all nodes in both trees. 14 """ 15 if not p and not q: 16 return True 17 if not p or not q: 18 return False 19 return ( 20 p.val == q.val 21 and self.isSameTree(p.left, q.left) 22 and self.isSameTree(p.right, q.right) 23 )
We can recursively define the same tree as follows:
- if the two tree nodes are null
- if the two tree nodes are non-null and they have the same value. We then apply the same rule to all nodes in both trees.
def
test():