首页 > 编程知识 正文

搜索二叉树删除节点,二叉树查找路径规则

时间:2023-05-03 23:53:52 阅读:117315 作者:2901

6使用二叉树搜索节点和父节点(5分) ) ) ) ) ) )。

写程序在二叉树中查找指定的节点和父节点。 二叉树节点的数据字段值不等于0的整数。

输入格式:输入一组以空格分隔的整数。 这表示具有空指针信息的二叉树的第一个根序列。 其中,空指针用0表示。 例如,1 5 8 0 0 0 6 0 0表示下图所示的二叉树。 第二行是整数m,表示查询的数量。 以下m行为整数k,而不是每行0,表示要搜索的节点的数据值: m为100以下,二叉树的节点数为150000以下,高度为6000以下。 输入数据保证二叉树各节点的数据值不相等。

输出格式:输出是m行,每行一个整数表示被搜索节点k的父节点数据值,在二叉树中没有节点k或节点k中没有父节点时输出0。

输入样本:158006003816以输出样本: 501

# include iostream # include queue # include string # includes stream # include unordered _ mapusingnamespacestd; 类树; 类节点{ string data; BNode *lch,*rch; public:bnode(3360lch(null ),rch (null ) ) { } bnode (string item,BNode *left=NULL,BNode *right=NULL ) ) 33333330 (; 类别树{ private : bnode * root; 公共: btree (:根) null ) {}~BTree ); voidpreoderbuild(bnode*Bt,int index,BNode* father,unordered_mapstring,string* mpFindFaher ); bode * SF (字符串值); (; 向量字符串树; BNode *BT=NULL; int CntLeft,CntRight; void BNode:Release () if (lch ) {lch-Release ); 删除通道; lch=空; (if ) rch ) ) {rch-Release; 删除通道; rch=NULL; }}BTree:~BTree (() /析构函数if (Bt ) ) {BT-Release ); delete BT; BT=NULL; } void btree : preoderbuild (bnode * Bt,int index,BNode* father,unordered_mapstring,string* mpFindFaher ) 索引; }else {BT=new BNode; BT-data=tree[index]; if () mpfindfaher ).find(Bt-data )!=(mpfindfaher ).end ) ) if(father!=null((mpfindfaher ) [BT-data]=father-data; } }索引; preoderbuild(BT-lch、index、Bt、mpFindFaher ); preoderbuild(BT-rch、index、Bt、mpFindFaher ); } }队列节点* q; 查找bode * btree :3360 SF (字符串值)//父节点q.push ) Bt ); BNode*ptr; ptr=Q.front (; while (! Q.empty () ) {ptr=Q.front; Q.pop (; if(ptr-lch ) if ) ptr-lch-data==value ) {cout ptr-data endl; 返回ptr; }if(ptr-rch ) if ) ptr-rch-data==value ) {cout ptr-data endl; 返回ptr; }if(ptr-lch ) q.push (ptr-lch ); (if ) ptr-rch ) q.push ) ptr-rch; }}cout 0 endl; }intmain((stringstr='15800060 ); 获取线(CIN,str ); 流流流(str; wile(sstream ) {string substr; sstream substr; tree.push_back(substr ); }BTree L; 索引=0; int m; cin m; 字符串字段; vectorstring vec_child; unordered_mapstring,string mp; wile(m---- ) {cin child; mp[child]='0'; VEC_child.push_back(child; }l.preoderbuild(Bt,index,NULL,mp ); for(autostr:vec_child ) {cout mp[str] endl; (L.(Btree ); 返回0; (/)1)5)8)0(6)0) /

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。