方法一:递归
class Solution: def TreeDepth(self , pRoot: TreeNode) -> int: # write code here if not pRoot: return 0 left = right =0 if pRoot.left: left = self.TreeDepth(pRoot.left) if pRoot.right: right = self.TreeDepth(pRoot.right) return max([left,right])+1方法二:层次遍历,每经历一层, count+=1
class Solution: def TreeDepth(self , pRoot: TreeNode) -> int: # write code here if pRoot is None: return 0 count = 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