struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
n 個節點的二叉鏈表含 n+1 個空鏈域。
// 先序:根 → 左 → 右
void preorder(TreeNode* root) {
if (!root) return;
cout << root->val << ' ';
preorder(root->left);
preorder(root->right);
}
// 中序:左 → 根 → 右
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
cout << root->val << ' ';
inorder(root->right);
}
// 後序:左 → 右 → 根
void postorder(TreeNode* root) {
if (!root) return;
postorder(root->left);
postorder(root->right);
cout << root->val << ' ';
}
class BinaryTree {
TreeNode* root;
public:
BinaryTree() : root(nullptr) {}
void insert(int val) { // BST 插入示例
TreeNode** cur = &root;
while (*cur) {
if (val < (*cur)->val) cur = &(*cur)->left;
else cur = &(*cur)->right;
}
*cur = new TreeNode(val);
}
void preOrder() { preorder(root); cout << endl; }
void inOrder() { inorder(root); cout << endl; }
void postOrder() { postorder(root); cout << endl; }
int countNodes(TreeNode* n) { return n ? countNodes(n->left)+countNodes(n->right)+1 : 0; }
int countLeaves(TreeNode* n) { return n ? (n->left||n->right ? countLeaves(n->left)+countLeaves(n->right) : 1) : 0; }
// ... 其他操作
};
中序非遞歸為例:
void inorderIter(TreeNode* root) {
stack st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) { st.push(cur); cur = cur->left; }
cur = st.top(); st.pop();
cout << cur->val << ' ';
cur = cur->right;
}
}