编写函数,以一颗树的根为输入,返回一颗对应的二叉树,给出c++代码
时间: 2024-04-29 20:25:53 浏览: 118
以下是一个示例代码,树的节点结构体定义为Node,二叉树的节点结构体定义为BinaryNode:
```
typedef struct Node {
int val;
Node* left;
Node* right;
Node* next;
} Node;
typedef struct BinaryNode {
int val;
BinaryNode* left;
BinaryNode* right;
} BinaryNode;
BinaryNode* constructBinaryTree(Node* root) {
if (root == NULL) {
return NULL;
}
BinaryNode* binaryRoot = (BinaryNode*)malloc(sizeof(BinaryNode));
binaryRoot->val = root->val;
binaryRoot->left = NULL;
binaryRoot->right = NULL;
Node* curr = root;
while (curr != NULL) {
BinaryNode* binaryCurr = binaryRoot;
while (binaryCurr != NULL) {
if (curr->left != NULL) {
binaryCurr->left = (BinaryNode*)malloc(sizeof(BinaryNode));
binaryCurr->left->val = curr->left->val;
binaryCurr->left->left = NULL;
binaryCurr->left->right = NULL;
}
if (curr->right != NULL) {
binaryCurr->right = (BinaryNode*)malloc(sizeof(BinaryNode));
binaryCurr->right->val = curr->right->val;
binaryCurr->right->left = NULL;
binaryCurr->right->right = NULL;
}
binaryCurr = binaryCurr->next;
curr = curr->next;
}
curr = binaryCurr = binaryRoot->left;
binaryRoot->left = binaryRoot->right = NULL;
}
return binaryRoot;
}
```
该函数的实现方式是利用树的next指针,按层遍历树,并将每个节点的左右子节点依次加入到二叉树的左右节点中。
阅读全文