剑指offer39. 平衡二叉树

原题

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

Reference Answer

思路分析

只是在上一题寻找最大深度的基础上加了平衡树判定条件而已:即左右子树的深度相差不能超过1。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if pRoot is None:
            return True
        left = self.getDepth(pRoot.left)
        right = self.getDepth(pRoot.right)
        if abs(left - right) > 1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.left)

    def getDepth(self, root):
        if root is None:
            return 0
        nleft = self.getDepth(root.left)
        nright = self.getDepth(root.right)
        return max(nleft, nright) + 1

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84310398