1. 程式人生 > >【劍指offer】二叉樹的深度python實現

【劍指offer】二叉樹的深度python實現

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

思路:深度使用遞迴

# -*- 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
        #遞迴函式,呼叫solution
        leftDepth= Solution.TreeDepth(self,pRoot.left);
        rightDepth= Solution.TreeDepth(self,pRoot.right);
        if leftDepth>rightDepth:
            return leftDepth+1
        else: return rightDepth+1