zoukankan      html  css  js  c++  java
  • 1.把2叉查找树转换成双向链表

    参考线索二叉树的建立方法,对二叉查找树进行中序遍历,遍历中保存1个pre指针,指向刚刚访问过的节点,即当前节点的中序前驱。

    代码如下:

    #include<iostream>
    #include<cstdlib>
    using namespace std;
    
    typedef struct node
    {
    	int data;
    	struct node* left;
    	struct node* right;
    }Tree;
    
    
    //输入二叉查找树的先序顺序,NULL指针用0代替
    Tree* create(void)
    {
    	int d;
    	Tree *root=NULL;
    
    	//按先序输入,NULL指针是0
    	cin>>d;
    	if(d==0)
    		return NULL;
    	else
    	{
    		root=(Tree*)malloc(sizeof(Tree));
    		root->data=d;
    		root->left=create();
    		root->right=create();
    	}
    	return root;
    }
    
    
    
    //参考线索二叉树
    Tree* pre=NULL;
    void inorder2(Tree* t)
    {
    	if(t)
    	{
    		Tree* left=t->left;
    		Tree* right=t->right;
    		inorder2(left);
    
    		t->left=pre;
    		if(pre!=NULL)
    			pre->right=t;
    		pre=t;
    		
    		inorder2(right);
    	}
    }
    
    
    //遍历这个双向链表
    void bianli(Tree* t)
    {
    	while(t->left!=NULL)
    		t=t->left;
    
    	Tree* temp=t;
    	while(temp!=NULL)
    	{
    		cout<<temp->data<<" ";
    		temp=temp->right;
    	}
    	cout<<endl;
    }
    
    void del(Tree* t)
    {
      Tree *pre=NULL;
      
      while(t->left!=NULL)
        t=t->left;
      while(t)
      {
        pre=t;
        t=t->right;
        free(pre);
      }
    } int main(void) { Tree* root=NULL; root=create(); inorder2(root); bianli(root);       
         del(root);
    return 0; }

    例子输入: 输入 10 6 4 0 0 8 0 0 14 12 0 0 16 0 0建立树,输出结果是4 6 8 10 12 14 16 

    试的另外一种方法,即在中序递归通过查找节点的中序前驱和中序后继,然后改变节点left和right指针值,这是错误的,因为中序中,后面的节点可能会用到前面节点的left,right孩子信息去找前驱或后继。

  • 相关阅读:
    编辑器 --- Visual Studio Code 英文界面转换成中文(简体)
    CSS3 -- column 实现瀑布流布局
    CSS3 -- 边框圆角
    CSS3 -- 弹性盒
    自适应布局要素
    Vue -- 基础知识
    Vue -- element-ui el-table 的合计在第一行显示并可点击
    如何在网页标题栏title加入logo(icon)图标?
    linux下暴力破解工具hydra【转】
    linux 服务简介
  • 原文地址:https://www.cnblogs.com/buxianghe/p/3194508.html
Copyright © 2011-2022 走看看