劍指Offer(Python多種思路實現):二叉樹的深度
面試55題:
題目:二叉樹的深度
題:輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
解題思路一:
①如果一棵樹只有一個節點,它的深度爲1
②如果根節點只有左子樹而沒有右子樹,那麼樹的深度是左子樹的深度加1
同樣,如果根節點只有右子樹而沒有左子樹,那麼樹的深度是右子樹的深度加1
既有右子樹又有左子樹時,數的深度是左子樹和右子樹深度較大者加1
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left,right)+1
解題思路二:迭代
def maxDepth(self, root: 'TreeNode') -> 'int':
q = root and collections.deque([(root, 1)])
d = 0
while q:
node, d = q.popleft()
if node.right:
q.append((node.right, d+1))
if node.left:
q.append((node.left, d+1))
return d