题解 | #二叉排序树#

二叉排序树

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

		}
	}
}

全部评论

相关推荐

点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务