**《剑指offer》39:平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

平衡二叉树:

平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

C++实现:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL)
            return true;
        
        return abs(getdepth(pRoot -> left) - getdepth(pRoot -> right)) <= 1 && IsBalanced_Solution(pRoot -> left) && IsBalanced_Solution(pRoot -> right);
    }
    
    int getdepth(TreeNode *p)
    {
        if(p == NULL)
            return 0;
        
        return 1 + max(getdepth(p -> left), getdepth(p -> right));
    }
};

python实现:

# -*- 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
        def getdepth(p):
            if p == None:
                return 0
        
            return 1 + max(getdepth(p.left), getdepth(p.right))
        
        if pRoot == None:
            return True
        
        return abs(getdepth(pRoot.left) - getdepth(pRoot.right)) <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)

猜你喜欢

转载自blog.csdn.net/w113691/article/details/81179050
今日推荐