2026/5/28 17:44:03
网站建设
项目流程
有网页源码怎么做网站,做网站顶部图片长度是多少,舟山网络公司网站建设公司,电商网站开发服务器这一题的大意是给出一个二叉搜索树#xff0c;让我们判断是不是红黑树#xff0c;
只需要按题目要求构造好树#xff0c;然后判断它是不是符合红黑树的条件即可。
题目给出了红黑树的性质#xff0c;我们只需要判断它是否满足即可。
需要我们对二叉搜索树#xff0c;建树让我们判断是不是红黑树只需要按题目要求构造好树然后判断它是不是符合红黑树的条件即可。题目给出了红黑树的性质我们只需要判断它是否满足即可。需要我们对二叉搜索树建树DFS掌握好完整代码如下#includebits/stdc.h#includeiostreamusingnamespacestd;//构造一棵二叉搜索树structnode{intdata;structnode*l;structnode*r;intcolor;};node*tostruct_tree(node*root,intx){if(rootnullptr){rootnew(node);root-datax;if(x0){root-color1;//表示黑色}else{root-color0;//表示红色}root-lnullptr;root-rnullptr;}elseif(abs(x)abs(root-data)){root-ltostruct_tree(root-l,x);}elseif(abs(x)abs(root-data)){root-rtostruct_tree(root-r,x);}returnroot;}intgetBlackHeight(node*x){if(xnullptr)return1;// NULL节点视为黑色属性3// 递归获取左右子树黑高intleftgetBlackHeight(x-l);intrightgetBlackHeight(x-r);if(left-1||right-1)return-1;// 下层已经发现不合法继续上传if(left!right)return-1;// 属性5不满足黑高不一致// 若当前是黑节点黑高 1returnleft(x-color1?1:0);}boolisredtree(node*root,boolflag){if(flag0){if(root-color0){returnfalse;}flag1;}if(root!nullptrroot-color0){//红色if(root-l!nullptrroot-l-color0){returnfalse;}if(root-r!nullptrroot-r-color0){returnfalse;}}if(getBlackHeight(root)-1)returnfalse;if(root-l!nullptr){if(!isredtree(root-l,1)){// cout1endl;returnfalse;}}if(root-r!nullptr){if(!isredtree(root-r,1)){returnfalse;}}returntrue;}intmain(){intK;cinK;for(inti0;iK;i){intN;cinN;node*rootnullptr;for(intj0;jN;j){intx;cinx;roottostruct_tree(root,x);}boolflag0;if(isredtree(root,flag)){coutYesendl;}else{coutNoendl;}}return0;}总结考察树的相关性质对基本知识点掌握扎实就好做。注意题目要求我刚开始就自己幻想出多余条件和理解错题意而写错在写代码的时候也难免会写出bug需要有较强的debug能力。