牛客网-C++剑指offer-第三十九题(平衡二叉树)

题目描述

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

 

解题思路:

平衡二叉树判断条件:

平衡二叉树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树、AVL、替罪羊树、Treap、伸展树等。 最小二叉平衡树的节点的公式如下 F(n)=F(n-1)+F(n-2)+1 这个类似于一个递归的数列,可以参考Fibonacci数列,1是根节点,F(n-1)是左子树的节点数量,F(n-2)是右子树的节点数量。(左图不平衡,右图平衡)

牛客网-C++剑指offer-第三十九题(平衡二叉树)_第1张图片

 

参考代码:

#include 
#include 
#include 
#include 
#include 
#include
#include 

using namespace std;


struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
};

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == NULL)
            return true;

        int diff = abs(find_depth(pRoot->left) - find_depth(pRoot->right));
        if (diff > 1)
            return false;

        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);


    }

    int find_depth(TreeNode* root)
    {
        if (root == NULL)
            return 0;

        int left = find_depth(root->left);
        int right = find_depth(root->right);

        return max(left+1,right+1);
    }
};




int main()
{
    Solution solution;

    TreeNode TreeNode9 = {9,NULL,NULL};
    TreeNode TreeNode8 = {8,NULL,NULL};
    TreeNode TreeNode7 = {7,NULL,NULL};
    TreeNode TreeNode6 = {6,NULL,&TreeNode9};
    TreeNode TreeNode5 = {5,NULL,NULL};
    TreeNode TreeNode4 = {4,NULL,NULL};
    TreeNode TreeNode3 = {3,&TreeNode6,&TreeNode7};
    TreeNode TreeNode2 = {2,&TreeNode4,&TreeNode5};
    TreeNode TreeNode1 = {1,&TreeNode2,&TreeNode3};

    if (solution.IsBalanced_Solution(&TreeNode1))
    {
        cout<<"true"<

 

你可能感兴趣的:(牛客网-C++剑指offer-第三十九题(平衡二叉树))