【2】输入一颗二叉树判断是不是平衡二叉树

来源:互联网 发布:古典白话小说推荐知乎 编辑:程序博客网 时间:2024/05/18 03:49

题目:输入一颗二叉树的根结点,判断该二叉树是不是平衡二叉树。平衡二叉树是满足所有结点的左右子树的高度差不超过1的二叉树


方案一:遍历数组的每一个结点,对每一个结点求它的左右子树的高度并进行判断。时间复杂度大于O(n),小于O(n^2)效率较低,因为有很多点需要重复访问。

//二叉树的结点struct BinaryTreeNode{     int m_value;     BinaryTreeNode *m_lson;     BinaryTreeNode *m_rson;};//求二叉树的深度int GetDepth(BinaryTreeNode *root){if(root == NULL){   return 0;}int lsonDepth = GetDepth(root->m_lson);int rsonDepth = GetDepth(root->m_rson);return lsonDepth < rsonDepth ? (rsonDepth+1) : (lsonDepth+1);}//方案一对每个结点进行判断bool IsBalanced(BinaryTreeNode *root){if(root == NULL){    return true;}int lsonDepth = GetDepth(root->m_lson);int rsonDepth = GetDepth(root->m_rson);int dis = lsonDepth-rsonDepth;if((dis <= 1) && (dis >= -1)){return IsBalanced(root->m_lson) && IsBalanced(root->m_rson);}else{    return false;}} 


方案二:利用二叉树的后序遍历,对于先访问左右子树,然后对每个根结点进行判断,传入一个高度的参数即可。时间复杂度为O(n)。

//二叉树的结点struct BinaryTreeNode{     int m_value;     BinaryTreeNode *m_lson;     BinaryTreeNode *m_rson;};//后序遍历判断是不是平衡二叉树bool IsBalanced(BinaryTreeNode *root, int *depth){if(root == NULL){    *depth = 0;    return true;}int lsonDepth = 0;int rsonDepth = 0;if(IsBalanced(root->m_lson, &lsonDepth) && IsBalanced(root->m_rson, &rsonDepth)){    int dis = lsonDepth-rsonDepth;if((dis >= -1) && (dis <= 1)){    *depth = 1+(lsonDepth < rsonDepth ? rsonDepth : lsonDepth);    return true;}else{    return false;}}else{    return false;}}



2 0