方法一:基本方法 不做解释了
class Solution { public: int shendu(TreeNode* &root) { if(root==NULL) { return 0; } int zuozishu=shendu(root->left); int youzishu=shendu(root->right); return (zuozishu<youzishu?youzishu+1:zuozishu+1); } //遍历 bool IsBalanced_Solution(TreeNode* pRoot) { if(pRoot==NULL) { return true; } int leftdepth=shendu(pRoot->left); int rightdepth=shendu(pRoot->right); int chazhi=abs(leftdepth-rightdepth); if(chazhi>1) { return false; } return(IsBalanced_Solution(pRoot->right)&&IsBalanced_Solution(pRoot->left)); } };
方法二:由于上述方法在求该结点的的左右子树深度时遍历一遍树,再次判断子树的平衡性时又遍历一遍树结构,造成遍历多次。因此方法二是一边遍历树一边判断每个结点是否具有平衡性。
bool IsBalanced(BinaryTreeNode* pRoot, int* depth) { if(pRoot== NULL) { *depth = 0; return true; } int nLeftDepth,nRightDepth; bool bLeft= IsBalanced(pRoot->m_pLeft, &nLeftDepth); bool bRight = IsBalanced(pRoot->m_pRight, &nRightDepth); if (bLeft && bRight) { int diff = nRightDepth-nLeftDepth; if (diff<=1 || diff>=-1) { *depth = 1+(nLeftDepth > nRightDepth ? nLeftDepth : nRightDepth); return true; } } return false; } bool IsBalanced(BinaryTreeNode* pRoot) { int depth = 0; return IsBalanced(pRoot, &depth); }