方法一: //求當(dāng)前節(jié)點(diǎn)的高度 int level(TreeNode *root) { if(root == NULL) return 0; return 1 + max(level(root->left),level(root->right)); } bool isBalanced(TreeNode *root) { if(root == NULL) return true; int factor = abs(level(root->left) - level(root->right)); return factor < 2 && isBalanced(root->left) && isBalanced(root->right); } 方法二:一種更好的方法 isBalanced返回當(dāng)前節(jié)點(diǎn)的高度,,-1代表樹不是平衡二叉樹,將計(jì)算結(jié)果自底向上傳遞,,并且確保每個(gè)節(jié)點(diǎn)只計(jì)算一次,,復(fù)雜度為O(n)。 int isBalancedHelper(TreeNode *root) { if(root == NULL) return 0; int Lh = isBalancedHelper(root->left); if(Lh == -1) return -1; int Rh = isBalancedHelper(root->right); if(Rh == -1) return -1; if(abs(Lh - Rh) > 1) return -1; return max(Lh,Rh) + 1; } bool isBalancedTree(TreeNode *root) { if(root == NULL) return true; return (isBalancedHelper(root) != -1); } |
|