您的位置:首页 > 其它

各种方法建立二叉树

2016-05-25 20:14 375 查看

各种方法建立二叉树

//非递归建立二叉树

struct node{
char data;
node* left;
node* right;
};

void createtree() {
node* q;
node* tree[max];
int i, j;
char val;
node* root = NULL;
cin >> i >> val;
while (i != 0&& val != '#') {  //输入结束标志
q = new node;
q->data = val;
q->left = NULL;
q->right = NULL;
tree[i] = q;
if (i == 1) {
root = q;
} else {
j = i/2;
if (i%2 == 0) {
tree[j]->left = q;
} else {
tree[j]->right = q;
}
}
cin >> i >> val;
}
}

//队列建立二叉树
BinaryTree(vector<char> & a) { // 将vector中的数据构建成二叉树
node* root;
if (a.empty()) {
root = NULL;
return;
} else {
std::queue<Node**> queue_node;
root = new Node(a[0]);
queue_node.push(&root->left);
queue_node.push(&root->right);
int i = 1;
int n = a.size();
while (i < n) {
Node** temp = queue_node.front();
queue_node.pop();
if (i >= a.size()) {
temp = NULL;
i++;
} else {
*temp = new Node(a[i]);
queue_node.push(&((*temp)->left));
queue_node.push(&((*temp)->right));
i++;
}
}
}
}

//递归建立二叉树
void creat_tree(node* &root) {
char ch;
cin >> ch;
if (ch == '0') { //  代表子节点为空
root = NULL;
} else {
root = new node;
root->data = ch;
creat_tree(root->lchild);
creat_tree(root->rchild);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: