题解 | #二叉排序树#
二叉排序树
https://www.nowcoder.com/practice/30a0153649304645935c949df7599602
注意引用符号千万不可缺失
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode{
int data;
TreeNode* leftchild;
TreeNode* rightchild;
};
TreeNode * Buildtree(int n, TreeNode * & root,int father) { //TreeNode * p只是一个指向Treenode的指针,并没有完成初始化
if (root == NULL) {
root = new TreeNode; //为p结点申请一片内存空间
root->data = n;
root->leftchild = NULL;
root->rightchild = NULL;
cout << father << endl;
}
else if (n > root->data) { //连接右子树
root->rightchild = Buildtree(n, root->rightchild,root->data);
}
else if (n < root->data) { //连接右子树
root->leftchild = Buildtree(n, root->leftchild,root->data);
}
return root;
}
int main() {
int num, n[100];
while (cin >> num) {
TreeNode * root=NULL;
for (int i = 0; i < num; i++) {
cin >> n[i];
Buildtree(n[i],root,-1);
}
}
}
海康威视公司福利 1322人发布