输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof
用层序遍历:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
count = 0
stack = [root]
while stack:
count+=1
next_stack=[]
for node in stack:
if node.left:
next_stack.append(node.left)
if node.right:
next_stack.append(node.right)
stack = next_stack
return count
用前序写递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
self.max_depth = 0
def loop(root,depth):
if not root:
return
depth+=1
self.max_depth=max(self.max_depth,depth)
loop(root.left,depth)
loop(root.right,depth)
loop(root,0)
return self.max_depth
只用一个参数,不把层数加进去递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
l = 1+self.maxDepth(root.left)
r = 1+self.maxDepth(root.right)
return max(l,r)