39-判斷二叉樹是否爲平衡二叉樹【樹的深度&後序遍歷】

一、問題描述

輸入一棵二叉樹的根節點,判斷該樹是不是平衡二叉樹。如果某二叉樹中任意結點的左右子樹的深度相差不超過1,那麼它就是一棵平衡二叉樹。

二、解題思路

思路一:先遞歸求各結點的深度,根據深度做差值,根據差值判斷是否爲平衡二叉樹
思路二:後序遍歷二叉樹,在遍歷的同時記錄深度---避免思路一的重複計算

三、解題算法

1、思路1:根據深度求差值

/******************************
author:tmw
date:2018-8-6
******************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct BiTreeNode
{
    int data;
    struct BiTreeNode* lchild;
    struct BiTreeNode* rchild;
}BiTreeNode;

/**遞歸求二叉樹的深度**/
int TreeDepth( BiTreeNode* root )
{
    //遞歸收斂條件--初始條件
    if( root == NULL ) return 0;

    int left = TreeDepth(root->lchild);
    int right = TreeDepth(root->rchild);

    return left>right?left+1:right+1;
}

/**判斷二叉樹是否爲平衡二叉樹**/
bool isBalanceTree( BiTreeNode* root )
{
    //遞歸收斂條件--初始條件
    if( root == NULL ) return true;

    //分別求左右子樹的深度
    int left_depth = TreeDepth(root->lchild);
    int right_depth = TreeDepth(root->rchild);

    //計算左右深度差值
    int diff = left - right;
    if( diff > 1 || diff < -1 )
        return false;

    return isBalanceTree(root->lchild) && isBalanceTree(root->rchild);
}

2、思路2:後序遍歷,同時記錄深度

/**思路二:後序遍歷二叉樹,在遍歷的同時記錄深度**/
bool isBalanceTreeMethod2( BiTreeNode* root, int* depth )
{
    if( root == NULL )
        return true;

    int left, right;
    if( isBalanceTreeMethod2(root->lchild, &left) && isBalanceTreeMethod2(root->rchild, &right) )
    {
        int diff = left - right;
        if( diff <= 1 && diff >= -1 )
        {
            *depth = left > right ? 1+left : 1+right;
            return true;
        }
    }
    return false;
}

 

                                                                                                     夢想還是要有的,萬一實現了呢~~~~~ヾ(◍°∇°◍)ノ゙~~~~~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章