1. 程式人生 > >【劍指Offer】38二叉樹的深度

【劍指Offer】38二叉樹的深度

題目描述

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。

時間限制:1秒;空間限制:32768K;本題知識點:樹

解題思路

遞迴求解

# -*- 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 == None:
            return 0
        a,b,c = 0,0,0
        if pRoot.left!= None:
            a = self.TreeDepth(pRoot.left) + 1
        if pRoot.right!= None:
            b =  self.TreeDepth(pRoot.right) + 1
        if pRoot.left==None and pRoot.right== None:
            c = 1
        return max(a,b,c)