1. 程式人生 > >平衡二叉樹[劍指offer]之python實現

平衡二叉樹[劍指offer]之python實現

題目描述

輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。

題目連結

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def getDepth(self , Root):
        if Root == None:
            return 0;
        lDepth = self.getDepth(Root.left);
        rDepth = self.getDepth(Root.right);
        return
max(lDepth , rDepth) + 1; def IsBalanced_Solution(self, pRoot): if not pRoot: return True lDepth = self.getDepth(pRoot.left); rDepth = self.getDepth(pRoot.right); diff = lDepth - rDepth; if diff < -1 or diff > 1: return False
; return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right);

求解:為什麼用val不可以記錄樹的高度?