輸入二叉樹根節點,判斷是否為平衡二叉樹:任意節點的左右子樹深度差不超過 1。
對每個節點,分別計算左右子樹深度,再遞歸判斷左右子樹是否平衡。
int TreeDepth(TreeNode* root) {
if (!root) return 0;
int left = TreeDepth(root->left);
int right = TreeDepth(root->right);
return max(left, right) + 1;
}
bool IsBalanced(TreeNode* root) {
if (!root) return true;
if (!IsBalanced(root->left)) return false;
if (!IsBalanced(root->right)) return false;
int leftDepth = TreeDepth(root->left);
int rightDepth = TreeDepth(root->right);
return abs(leftDepth - rightDepth) <= 1;
}
缺點:深度被重複計算多次,時間復雜度 O(n²)(斜樹最壞情況)。
在判斷平衡的同時計算深度,通過引用參數返回子樹深度,避免重複遍歷。
bool IsBalancedCore(TreeNode* root, int& depth) {
if (!root) {
depth = 0;
return true;
}
int leftDepth, rightDepth;
if (!IsBalancedCore(root->left, leftDepth)) return false;
if (!IsBalancedCore(root->right, rightDepth)) return false;
depth = max(leftDepth, rightDepth) + 1;
return abs(leftDepth - rightDepth) <= 1;
}
bool IsBalancedTree(TreeNode* root) {
int depth;
return IsBalancedCore(root, depth);
}
| 特性 | 方案一 O(n²) | 方案二 O(n) |
|---|---|---|
| 遍歷方式 | 自頂向下,多次重複遍歷 | 自底向上,每節點僅遍歷一次 |
| 深度計算 | 獨立函數重複計算 | 判斷過程中順便計算 |
| 適用場景 | 教學理解、小規模數據 | 工程實踐、大規模數據 |