Im在實現二進制搜索樹的過程中,該樹使用Array實現來表示。這是我到目前爲止的代碼:請注意,我已完成樹的結構並將其保存爲鏈接列表。我想將這個鏈表轉換成一個數組。二進制搜索樹數組實現C++
我對如何去做這件事的想法如下。做一個return_array函數。將數組大小設置爲最大節點數(2 ^(n-1)+1)並遍歷鏈表。根節點將在數組上@ postion 0,然後是他的L-child =(2 * [index_of_parent] +1)和R-child =(2 * [index_of_parent] +2)。我環顧四周,搜索了一些可以讓我知道如何保持每個節點的粘性以及如何通過每個節點的東西。
我是否在解決這個問題? 有沒有遞歸?
另外我正在考慮創建一個可視化樹而不是一個數組,但不知道如何正確地將其分隔開。如果任何人有關於如何做到這一點的想法,那麼更好地理解這一點將是非常棒的。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
void inorder(struct node* node){
if(node){
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
}
void insert(struct node** node, int key){
if(*node == NULL){
(*node) = (struct node*)malloc(sizeof(struct node));
(*node)->data = key;
(*node)->left = NULL;
(*node)->right = NULL;
printf("inserted node with data %d\n", (*node)->data);
}
else if ((*node)->data > key){
insert((&(*node)->left),key);
}
else
insert((&(*node)->right),key);
}
int max_tree(struct node* node){
int left,right;
if(node == NULL)
return 0;
else
{
left=max_tree(node->left);
right=max_tree(node->right);
if(left>right)
return left+1;
else
return right+1;
}
}
//This is where i dont know how to keep the parent/children the array.
void return_array(struct node* node, int height){
int max;
height = height - 1;
max = pow(2, height) - 1;
int arr [height];
}
int main(){
int h;
struct node* root = NULL;
insert(&root, 10);
insert(&root, 20);
insert(&root, 5);
insert(&root, 2);
inorder(root);
cout << endl;
cout << "Height is: ";
cout << max_tree(root);
h = max_tree(root)
return_array(root, h)
}
用數組表示二叉搜索樹並不是一個好主意,除非您知道關於數據的特定信息 – aaronman