int main() { TreeNode *root, *p, *pp; Initiate(&root); p = InsertLeftNode(root, 'A'); p = InsertLeftNode(p, 'B'); pp=p; p = InsertLeftNode(p, 'D'); p = InsertRightNode(pp, 'E'); p = InsertLeftNode(p, 'H'); p = InsertRightNode(root->leftChild, 'C'); pp = p; InsertLeftNode(p, 'F'); p = InsertRightNode(p, 'I'); InsertRightNode(pp, 'G'); PrintBiTree(root->leftChild, 1); return 0; }改变代码让I成为F的左子树
时间: 2023-07-15 07:10:57 浏览: 78
leetcode–617. 合并二叉树
可以将原来的代码中的以下几行修改:
```
pp = p;
p = InsertRightNode(p, 'I');
InsertRightNode(pp, 'G');
```
改为:
```
pp = p->leftChild;
p->leftChild = InsertRightNode(p->leftChild, 'I');
InsertRightNode(pp, 'G');
```
这样就可以将I成为F的左子树了。完整代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode *leftChild;
struct TreeNode *rightChild;
} TreeNode;
void Initiate(TreeNode **root) {
*root = (TreeNode*)malloc(sizeof(TreeNode));
(*root)->data = '\0';
(*root)->leftChild = NULL;
(*root)->rightChild = NULL;
}
TreeNode* InsertLeftNode(TreeNode *p, char x) {
TreeNode *newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = x;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
p->leftChild = newNode;
return newNode;
}
TreeNode* InsertRightNode(TreeNode *p, char x) {
TreeNode *newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = x;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
p->rightChild = newNode;
return newNode;
}
void PrintBiTree(TreeNode *p, int depth) {
if (p != NULL) {
PrintBiTree(p->rightChild, depth+1);
for (int i = 0; i < depth-1; i++) {
printf(" ");
}
if (depth > 0) {
printf("---");
}
printf("%c\n", p->data);
PrintBiTree(p->leftChild, depth+1);
}
}
int main() {
TreeNode *root, *p, *pp;
Initiate(&root);
p = InsertLeftNode(root, 'A');
p = InsertLeftNode(p, 'B');
pp = p->leftChild;
p = InsertLeftNode(p, 'D');
p = InsertRightNode(pp, 'E');
p = InsertLeftNode(p, 'H');
p =RightNode(root->leftChild, 'C');
pp = p->leftChild;
p->leftChild = InsertRightNode(p->leftChild, 'F');
p = InsertRightNode(p, 'I');
InsertRightNode(pp, 'G');
PrintBiTree(root->leftChild, 1);
return 0;
}
```
阅读全文