100. Same Tree

2021. 11. 12. 16:06Leetcode

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)

'Leetcode' 카테고리의 다른 글

102. Binary Tree Level Order Traversal  (0) 2021.11.14
104. Maximum Depth of Binary Tree  (0) 2021.11.12
143. Reorder List  (0) 2021.11.12
19. Remove Nth Node From End of List  (0) 2021.11.12
367. Valid Perfect Square  (0) 2021.11.12