方法一:递归
# -*- 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 right = left = 0 if pRoot.left: left = self.TreeDepth(pRoot.left) if pRoot.right: right = self.TreeDepth(pRoot.right) return max([left,right])+1
方法二:层次遍历,每经历一层, count+=1
# -*- 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 count = 0 if not pRoot: return 0 now_layer = [pRoot] next_layer = [] while now_layer: for i in now_layer: if i.left: next_layer.append(i.left) if i.right: next_layer.append(i.right) count+=1 now_layer,next_layer = next_layer,[] return count