【PAT甲级真题】- Is It a Binary Search Tree (25)
题目来源Is It a Binary Search Tree (25)题目描述点击链接自行查看注意点这里的二叉搜索树大于等于插到右边思路简介一道二叉树模板题6202年了应该不会还有人不会写二叉树吧bushi一开始想到前序遍历不可能确定一棵树还以为题目错了后面发现题目说的是前序遍历是否有可能是一个二叉搜索树那其实就是按照前序遍历的顺序以此把给出点插入到二叉搜索树当中然后对建完的树进行一次前序遍历如果结果相同说明这个前序遍历是合法的否则就是不合法的然而题目中提到了镜像树也算镜像其实也很简单前序遍历的顺序是NLR即当前(now)-左边(left)-右边(right)镜像操作就是NRL判断镜像树只要按照正常的顺序插入之后看看镜像前序遍历是否和给出序列相同即可注意如果是镜像的由于我们的插入是正常的顺序所以镜像树输出后序遍历时必须也是镜像的需要再写一个镜像后续遍历遇到的问题后序遍历没有镜像WA了一次代码/** * https://www.nowcoder.com/pat/5/problem/4082 * 二叉树遍历模板 */#includebits/stdc.husingnamespacestd;structTreeNode{intkey;TreeNode*right,*left;TreeNode():key(0),right(nullptr),left(nullptr){}TreeNode(intk):key(k),right(nullptr),left(nullptr){}};voidinsert(TreeNode*root,TreeNode*node){if(!root){rootnode;return;}if(node-keyroot-key){insert(root-left,node);}else{insert(root-right,node);}}voidpreorder(TreeNode*root,vectorintres){if(!root)return;res.emplace_back(root-key);preorder(root-left,res);preorder(root-right,res);}voidmirro_preorder(TreeNode*root,vectorintres){if(!root)return;res.emplace_back(root-key);mirro_preorder(root-right,res);mirro_preorder(root-left,res);}voidpostorder(TreeNode*root,vectorintres){if(!root)return;postorder(root-left,res);postorder(root-right,res);res.emplace_back(root-key);}voidmirro_postorder(TreeNode*root,vectorintres){if(!root)return;mirro_postorder(root-right,res);mirro_postorder(root-left,res);res.emplace_back(root-key);}voidsolve(){intn;cinn;TreeNode*rootnullptr;vectorintinput(n);for(inti0;in;i){cininput[i];TreeNode*nodenewTreeNode(input[i]);insert(root,node);}vectorintres1,res2,res;preorder(root,res1);mirro_preorder(root,res2);if(res1input){coutYES\n;postorder(root,res);for(inti0;in;i)coutres[i] ;return;}if(res2input){coutYES\n;mirro_postorder(root,res);for(inti0;in;i)coutres[i] ;return;}coutNO;}intmain(){ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);//fstream in(in.txt,ios::in);cin.rdbuf(in.rdbuf());intt1;//cint;while(t--){solve();}return0;}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2455877.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!