题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
Solutions
看起来好像有点儿无从下手,但其实对树结构比较熟还是比较明显的。假设一棵树只有根节点,那么其深度为 1;如果只有左子树,那么其深度为左子树的深度加 1(加上的这个 1 是根节点带来的深度);同样的如果只有右子树,其深度为右子树的深度加 1;如果同时又左右子树,其深度为较大的那个子树的深度加 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
if pRoot is None:
return 0
left_depth = self.TreeDepth(pRoot.left)
right_depth = self.TreeDepth(pRoot.right)
return left_depth + 1 if left_depth > right_depth else right_depth + 1
# return max(left_depth, right_depth) + 1
# 运行时间:28ms
# 占用内存:5840k