Open robert-min opened 3 months ago
⏰ 소요 시간 : X 🗂️ 유형 : DFS
🖌️ 문제 풀이
# 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right))+1
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
max_depth = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
max_depth = max(depth, max_depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return max_depth
https://leetcode.com/problems/leaf-similar-trees/?envType=study-plan-v2&envId=leetcode-75
dfs 풀이
class Solution(object):
def leafSimilar(self, root1, root2):
def dfs(node, leaf_sequence):
if not node:
return
if not node.left and not node.right: # Leaf node
leaf_sequence.append(node.val)
dfs(node.left, leaf_sequence)
dfs(node.right, leaf_sequence)
leaf_sequence1 = []
leaf_sequence2 = []
dfs(root1, leaf_sequence1)
dfs(root2, leaf_sequence2)
return leaf_sequence1 == leaf_sequence2
stack 풀이
class Solution(object):
def find_leaf(self, root):
leaf = []
stack = [root]
while stack:
now = stack.pop()
if not now.left and not now.right:
leaf.append(now.val)
else:
if now.left:
stack.append(now.left)
if now.right:
stack.append(now.right)
return leaf
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
result1 = self.find_leaf(root1)
result2 = self.find_leaf(root2)
if result1 == result2:
return True
else:
return False
문제 추천 이유!!
문제 링크
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/?envType=study-plan-v2&envId=leetcode-75
*작성가이드 입니다.
아래는 comment 템플릿입니다.(복사해서 사용)