Leetcode
100. Same Tree
Leeter
2021. 11. 12. 16:06
Description:
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
'''
[1] top-down)
idea::
check whether cur values are same first.
check whether left-subtree and right-subtree are same or not.
code::
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
elif (p and not q) or (not p and q):
return False
return (p.val==q.val) and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
-T/C: O(n) # n==the number of nodes
-S/C: O(h) # h==height of trees
'''
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
elif (p and not q) or (not p and q):
return False
return (p.val==q.val) and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)