题目描述:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
这道题和剑指offer - 二叉树中和为某一值得路径 - python做法是类似的,只不过少了些判断条件。从根节点开始深度优先遍历所有可能的路经,并使用全局变量maxdepth来保存最大深度。
AC代码
class Solution:
def TreeDepth(self, pRoot):
# write code here
global maxdepth
maxdepth = 0
def DfsTree(root,depth = 0):
global maxdepth
if root:
depth += 1
isLeaf = None
if root.left == None and root.right == None:
isLeaf = True
if root.left:
DfsTree(root.left, depth)
if root.right:
DfsTree(root.right, depth)
if isLeaf and depth > maxdepth:
maxdepth = depth
if pRoot == None:
return 0
else:
DfsTree(pRoot)
return maxdepth
一种更简单的递归解决方法
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot == None:
return 0
lDepth = self.TreeDepth(pRoot.left)
rDepth = self.TreeDepth(pRoot.right)
return max(lDepth, rDepth) + 1