定義結構體
typedef struct TreeNode{
int data;
struct TreeNode *lChild, *rChild;
} TreeNode, *BinaryTree;
建立結點
TreeNode *newTreeNode(int data){
auto node = new TreeNode;
node->data = data;
node->lChild = node->rChild = NULL;
return node;
}
構造二叉樹
若從0開始編號,結點i的左孩子序號為2 i + 1,右孩子序號為2 i + 2
BinaryTree BinaryTreeBuilder(int arr[], BinaryTree &root, int i, int n){
if (i < n){
root = newTreeNode(arr[i]);
BinaryTreeBuilder(arr, root->lChild, 2 * i + 1, n);
BinaryTreeBuilder(arr, root->rChild, 2 * i + 2, n);
}
return root;
}
中序遍歷
void inOrder(BinaryTree root){
if (root){
inOrder(root->lChild);
cout << root->data << " ";
inOrder(root->rChild);
}
}
main函式
int main(){
BinaryTree root;
int arr[] = {1, 2, 3, 4, 5, 6, 6, 6, 6};
int len = sizeof(arr) / sizeof(int);
BinaryTreeBuilder(arr, root, 0, len);
inOrder(root);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結