這是一道考察二叉樹結構理解與組合數學的經典題目。
三個節點的二叉樹共有 5 種 不同拓撲結構。以下用圖形直觀展示(`0` 代表節點,`*` 代表空位):
形態 1:右傾鏈 ***0 **/*\ *0***0 形態 2:左傾鏈 ****0 ***/ **0 */ 0 形態 3:左子樹雙節點 **0 */ 0 *\ **0 形態 4:右子樹雙節點 0 *\ **0 */\ 0 形態 5:平衡型(根 + 左右孩子) 0 *\ **0 ***\ ****0
n 個節點的二叉樹形態數 = 第 n 個卡特蘭數:
C(n) = (2n)! / ((n+1)! * n!)
C(n) = Σ C(i) * C(n-1-i) (i=0..n-1)
即:左子樹 i 節點,右子樹 n-1-i 節點,根佔 1 節點。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node { struct Node *left, *right; } Node;
Node* clone(Node* root) {
if (!root) return NULL;
Node* n = malloc(sizeof(Node));
n->left = clone(root->left);
n->right = clone(root->right);
return n;
}
void printTree(Node* root, int depth) {
if (!root) { printf("%*s*\n", depth*2, ""); return; }
printTree(root->right, depth+1);
printf("%*s0\n", depth*2, "");
printTree(root->left, depth+1);
}
int main() {
// 手動構建 5 種形態驗證
// ... 略
printf("總計 5 種形態\n");
return 0;
}