![56. 2种方法判断二叉树是不是平衡二叉树[is balanced tree] 56. 2种方法判断二叉树是不是平衡二叉树[is balanced tree]](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
【本文链接】
http://www.cnblogs.com/hellogiser/p/is-balanced-tree.html
【题目】
输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如下图中的二叉树就是一棵平衡二叉树:
【分析】
之前的博文27.二元树的深度[BinaryTreeDepth]中介绍过如何求二叉树的深度。有了经验之后再解决这个问题,我们很容易就能想到思路。
【方案1】
先判断左右子树是不是平衡的,若平衡再求出左右子树的深度,若深度之差大于1,则不平衡。因为在遍历每个结点时都要求其左右子树的深度,因此时间复杂度是O(n^2)的。
【代码】
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> /* // binary tree node struct // Get depth of a binary tree // the depth of left sub-tree // depth is the binary tree // is balanced tree in O(n^2) |
【方案2】
在判断左右子树是否平衡的过程中把深度计算出来,这样在对父结点进行平衡判断时就可以不用再重复计算左右子树的深度了。其时间复杂度为O(n)。
【代码】
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 = ; return true; } int leftDepth, rightDepth; // get root depth without visiting left and right sub-trees // is balanced tree |
【参考】
http://zhedahht.blog.163.com/blog/static/25411174201142733927831/
http://blog.csdn.net/zjull/article/details/11646591
http://blog.csdn.net/luckyxiaoqiang/article/details/7518888
【本文链接】