AcWing 71. 二叉树的深度
原题链接
简单
作者:
将情怀讲泛滥的恶果
,
2021-04-04 15:30:11
,
所有人可见
,
阅读 275
bfs解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def treeDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth=self.bfs(root)
return depth
def bfs(self,root):
if not root:
return 0
q = [root]
level = 0
current_level_left = 1
next_level_left = 0
while q:
p = q.pop(0)
current_level_left -=1
if p.left:
q.append(p.left)
next_level_left +=1
if p.right:
q.append(p.right)
next_level_left +=1
if current_level_left==0:
level += 1
temp = next_level_left
current_level_left = temp
next_level_left = 0
return level
递归解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def treeDepth(self, root: TreeNode) -> int:
if not root:
return 0
left_depth = self.treeDepth(root.left)
right_depth = self.treeDepth(root.right)
return max(left_depth,right_depth) + 1
dfs解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def treeDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.dfs(root)
def dfs(self,tree):
if not tree:
return 0
return max(self.dfs(tree.left),self.dfs(tree.right))+1