二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
方法一:深度遍历
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.right),self.maxDepth(root.left))+1
方法二:广度遍历
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
queue=[root]
lenth=0
while queue:
tmp=[]
for node in queue:
if node.left:
tmp.append(node.right)
if node.right:
tmp.append(node.left)
queue=tmp
lenth +=1
return lenth