int isBalancedCore(TreeNode* root){ if(root == NULL) return 0; int left = isBalancedCore(root->left); int right = isBalancedCore(root->right); if(left == -1 || right == -1) return -1; if(abs(left - right) <= 1) return 1 + max(left, right); else return -1; }
bool isBalanced(TreeNode *root) { int res = isBalancedCore(root); if(res == -1) return false; else return true; }
bool isBalanced_Solution2(BinaryTreeNode* pRoot) { if(pRoot == NULL) { return true; } int depth = 0; return isBalancedCore(pRoot, &depth); }
//方法二:采用后续遍历的方法,增加一个记录层次的变量,每个结点只遍历一次 bool isBalancedCore(BinaryTreeNode* pRoot, int* pDepth) { if(pRoot == NULL) { *pDepth = 0; return true; } int left, right; if(isBalancedCore(pRoot->m_pLeft, &left) && isBalancedCore(pRoot->m_pRight, &right)) { int diff = left - right; if(diff <= 1 && diff >= -1) { *pDepth = 1 + ((left > right) ? left : right); return true; } } return false; }