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;	
    	}
    }
    

      

  • 相关阅读:
    计算中文混合字符串长度(一)
    PHP截取含中文的混合字符串长度的函数
    获取星座的JS函数
    获取生日对应星座的PHP函数
    简单的 jQuery 浮动层随窗口滚动滑动插件实例
    MD5算法实现
    70. Climbing Stairs QuestionEditorial Solution
    167. Two Sum II
    167. Two Sum II
    303. Range Sum Query
  • 原文地址:https://www.cnblogs.com/lsf90/p/3147147.html
Copyright © 2011-2022 走看看