給定乙個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:給定二叉樹 [3,9,20,null,null,15,7],
方法1:迭代
思路:二叉樹層次遍歷的層數即為樹的深度。
# definition for a binary tree node.
# class treenode(object):
# def __init__(self, x):
# self.val = x
# self.left = none
# self.right = none
class solution(object):
def maxdepth(self, root):
""":type root: treenode
:rtype: int
"""# 層次遍歷的層數
if not root:
return 0
stack = [root]
n = 0
while stack:
next_layer =
for root in stack:
# 在這個迴圈中會將root的左右子樹入棧,放在next_layer中,所以stack中存放的都是同一層的樹
# stack中有多少個元素就說明該層有多少個節點,就要將節點的值放進temp中。
if root.left:
if root.right:
n+=1
stack = next_layer
return n
方法2:遞迴
思路:找最大深度也就是找左子樹和右子樹中各自最大深度中最大的然後加1,同樣對於左子樹和右子樹的最大深度也要重複這種操作。
# definition for a binary tree node.
# class treenode(object):
# def __init__(self, x):
# self.val = x
# self.left = none
# self.right = none
class solution(object):
def maxdepth(self, root):
""":type root: treenode
:rtype: int
"""# 遞迴
if not root:
return 0
return max(self.maxdepth(root.left)+1,self.maxdepth(root.right)+1)
LeetCode104二叉樹最大深度
給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 返回它的最大深度 3 definition for a binary tree node....
LeetCode 104 二叉樹的最大深度
題目描述 給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回它的最大深度 3 解題思路 此題可以用層次遍歷來解,每層設定乙個count值來...
leetcode 104 二叉樹的最大深度
給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 返回它的最大深度 3 definition for a binary tree node....