zoukankan      html  css  js  c++  java
  • 第十二章:二叉查找树(1)

    二叉查找树的基本操作

    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    stack<TreeNode *> s;
    
    typedef int Data;
    
    struct TreeNode{
    	Data data;
    	TreeNode *parent;
    	TreeNode *left;
    	TreeNode *right;
    };
    
    //创建一颗查找二叉树
    TreeNode *Create_Tree(int num){
    	TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode));
    	TreeNode *root,*child,*parent;
    	child=root=p;
    	p->parent=p->left=p->right=NULL;
    	cin>>root->data;
    	int i=0;
    	while (++i<num){
    		TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode));
    		p->parent=p->left=p->right=NULL;
    		cin>>p->data;
    		child=root;
    		while (child){
    			parent=child;
    			if (p->data>child->data){
    				child=child->right;
    			}else{
    				child=child->left;
    			}
    		}
    		if (p->data>parent->data){
    			parent->right=p;
    			p->parent=parent;
    		}else{
    			parent->left=p;
    			p->parent=parent;
    		}
    	}
    	return root;
    }
    
    TreeNode *Tree_Search(TreeNode *t,int key){
    	while (t&&t->data!=key){
    		if (t->data>key){
    			t=t->left;
    		}else{
    			t=t->right;
    		}
    	}
    	return t;
    }
    
    TreeNode *Minimum(TreeNode *t){
    	while (t->left){
    		t=t->left;
    	}
    	return t;
    }
    
    TreeNode *Maximum(TreeNode *t){
    	while (t->right){
    		t=t->right;
    	}
    	return t;
    }
    
    TreeNode *Tree_Successor(TreeNode *t){
    	if (t->right){
    		return Minimum(t->right);
    	}else{
    		while (t->parent&&t->parent->right==t){
    			t=t->parent;
    		}
    		return t->parent;
    	}
    }
    
    TreeNode *Tree_Predecessor(TreeNode *t){
    	if (t->left){
    		t=t->left;
    		while (t->right){
    			t=t->right;
    		}
    		return t;
    	}else if (t->parent){
    		return t->parent;	
    	}
    }
    

      

  • 相关阅读:
    Servlet介绍(一)
    iOS Dev (50)用代码实现图片加圆角
    Codeforces Round #265 (Div. 2) D. Restore Cube 立方体推断
    JVM:垃圾回收机制和调优手段
    Memcachedclient-XMemcached使用
    JVM中类的卸载机制
    血型统计
    iOS 事件传递及响应过程
    java 对象参数去空格方式
    spring aop 一个挡板例子
  • 原文地址:https://www.cnblogs.com/lsf90/p/3147147.html
Copyright © 2011-2022 走看看