题解 | #二叉排序树#

二叉排序树

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);

		}
	}
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-14 18:14
坐标某3线小城市,周休2天半,月工资1800老板给我发信息,我不去,结果她破防了……
职场不咸鱼:这人的意思是这份工作一直1800吗[掉小珍珠了休息也太少了,一天才六十几块钱。。。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务