您的位置:首页 > 编程语言 > C语言/C++

56. 2种方法判断二叉树是不是平衡二叉树[is balanced tree]

2014-05-25 22:58 267 查看

【本文链接】

http://www.cnblogs.com/hellogiser/p/is-balanced-tree.html

题目】

输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如下图中的二叉树就是一棵平衡二叉树:





分析

之前的博文27.二元树的深度[BinaryTreeDepth]中介绍过如何求二叉树的深度。有了经验之后再解决这个问题,我们很容易就能想到思路。

【方案1】

先判断左右子树是不是平衡的,若平衡再求出左右子树的深度,若深度之差大于1,则不平衡。因为在遍历每个结点时都要求其左右子树的深度,因此时间复杂度是O(n^2)的

【代码】

 C++ Code 
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52
 #include "stdafx.h"
#include <cmath>
#include <algorithm>

/*

    version: 1.0

    author: hellogiser

    blog: http://www.cnblogs.com/hellogiser

    date: 2014/5/25

*/

// binary tree node struct
struct BinaryTreeNode

{

    int value;

    BinaryTreeNode *left;

    BinaryTreeNode *right;

};

// Get depth of a binary tree
int TreeDepth(BinaryTreeNode *root)

{

    // the depth of a empty tree is 0
    if(NULL == root)

        return 0;

    // the depth of left sub-tree
    int nLeft = TreeDepth(root->left);

    // the depth of right sub-tree
    int nRight = TreeDepth(root->right);

    // depth is the binary tree
    return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);

    // return max(nLeft,nRight)+1;
}

// is balanced tree in O(n^2)
bool IsBalanced(BinaryTreeNode *root)

{

    if(NULL == root)

        return true;

    if(!IsBalanced(root->left))

        return false;

    if(!IsBalanced(root->right))

        return false;

    int leftDepth = TreeDepth(root->left);

    int rightDepth = TreeDepth(root->right);

    if (abs(leftDepth - rightDepth) > 1)

        return false;

    else

        return true;

}
【方案2】

在判断左右子树是否平衡的过程中把深度计算出来,这样在对父结点进行平衡判断时就可以不用再重复计算左右子树的深度了。其时间复杂度为O(n)

【代码】

 C++ Code 
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29
 // is balanced tree in O(n)
bool IsBalanced(BinaryTreeNode *root, int &depth)

{

    if(NULL == root)

    {

        depth = 0;

        return true;

    }

    int leftDepth, rightDepth;

    if(!IsBalanced(root->left, leftDepth))

        return false;

    if(!IsBalanced(root->right, rightDepth))

        return false;

    // get root depth without visiting left and right sub-trees
    depth = (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);

    if (abs(leftDepth - rightDepth) > 1)

        return false;

    else

        return true;

}

// is balanced tree
bool IsBalancedTree(BinaryTreeNode *root)

{

    int depth;

    return IsBalanced(root, depth);

}
【参考】

http://zhedahht.blog.163.com/blog/static/25411174201142733927831/

http://blog.csdn.net/zjull/article/details/11646591

http://blog.csdn.net/luckyxiaoqiang/article/details/7518888

【本文链接】

http://www.cnblogs.com/hellogiser/p/is-balanced-tree.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm 二叉树 c++