- struct BinaryTreeNode
- {
- int m_Value;
- BinaryTreeNode* m_pLeft;
- BinaryTreeNode* m_pRight;
- };
- int height(BinaryTreeNode*node ,bool&balance)
- {
- if(node==NULL)
- {
- return 0;}
- int R=node->right?height(node->right,balance)+1:0;
- if(!balance)
- return 0;
- int l=node->left?height(node->left,balance)+1:0;
- if(!balance)
- return 0;
- int dif=l-r;
- if (dif<=1)
- {
- return (l>r?l:r)
- }
- }
- bool isBalancedTree(node *root)
- {
- bool balance=tree;
- if(root)
- treehight(root,balance)
- return balance;
- }
//递归:
- struct BinaryTreeNode
- {
- int m_Value;
- BinaryTreeNode* m_pLeft;
- BinaryTreeNode* m_pRight;
- };
- int TreeDepth(BinaryTreeNode* pRoot)
- {
- if (pRoot == NULL)
- return 0;
- int nLeftDepth = TreeDepth(pRoot->m_pLeft);
- int nRightDepth = TreeDepth(pRoot->m_pRight);
- return (nLeftDepth>nRightDepth)?(nLeftDepth+1):(nRightDepth+1);
- }
判断该树是否为平衡二叉树
方法一:调用上述函数求每个节点的左右孩子深度
[cpp]
view plain
copy
print?
- bool IsBalanced(BinaryTreeNode* pRoot)
- {
- if(pRoot== NULL)
- return true;
- int nLeftDepth = TreeDepth(pRoot->m_pLeft);
- int nRightDepth = TreeDepth(pRoot->m_pRight);
- int diff = nRightDepth-nLeftDepth;
- if (diff>1 || diff<-1)
- return false;
- return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);
- }