劍指offer 38. 二叉樹的深度
阿新 • • 發佈:2018-11-25
原題
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。
Reference Answer
思路分析
想輕鬆一些,直接廣度優先搜尋,程式碼如下:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth (self, pRoot):
# write code here
if not pRoot:
return 0
self.res = []
path = [pRoot.val]
self.dfs(pRoot, path)
return max(self.res)
def dfs(self, root, path):
if not root.left and not root.right:
self.res.append( len(path))
if root.left:
self.dfs(root.left, path+[root.left.val])
if root.right:
self.dfs(root.right, path+[root.right.val])
進階版本:
由於題中已經明確是二叉樹,直接針對二叉樹進行深度查詢,可以進一步提升效率。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
lleft = self.findDepth(pRoot.left)
lright = self.findDepth(pRoot.right)
return max(lleft, lright)+1
def findDepth(self, root):
if not root:
return 0
length_left = self.findDepth(root.left)
length_right = self.findDepth(root.right)
return max(length_left, length_right) + 1