問題提出:
給定一個二叉樹,找出其最大深度。二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
解決思路:遞歸法求解。從根結點向下遍歷,每遍歷到子節點depth+1。
代碼實現( ̄▽ ̄):
# 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 root==None:
return 0
count = self.getDepth(root,0)
return count
def getDepth(self,node,count):
if node!=None:
num1 = self.getDepth(node.left,count+1);
num2 = self.getDepth(node.right,count+1);
num = num1 if num1>num2 else num2
return num
else:
return count
時間和空間消耗: