二叉树_二叉查找树

来源:互联网 发布:1.5厚js防水涂料用量 编辑:程序博客网 时间:2024/05/16 10:34

/*创建一颗树,判断是否为二叉查找树,递归先序遍历,非递归中序遍历*/

#include<iostream>

#include<string>
#include<queue>
#include<stack>
using namespace std;


/*二叉树结点*/
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};


/*链表结点*/
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


struct tempNode{
TreeNode *p_temp;
int height_temp;
}tempNode;


/*
    ListNode* getTreeLevel(TreeNode* root, int dep) {
        // write code here
TreeNode *p=root,*q;
int *listData;
int k=0;
listData=(int *)malloc(2^(dep-1)*sizeof(int));
int height=1;
tempNode * temp=NULL;
while(p)
{
if(height==dep-1)
{
if(p->left!=NULL)
{
listData[k++]=p->left->val;
}
if(p->right!=NULL)
{
listData[k++]=p->right->val;
}
//栈顶元素出栈为,p=栈顶.指针元素->right,height=栈顶高度+1;
}
}


//根据listData构建List

}
return 0;
    }
*/
bool check(TreeNode *root)// 判断是否BST
{
queue<TreeNode *> Q;
TreeNode *p=root;
Q.push(p);
while(!Q.empty())
{
TreeNode * front=Q.front();
cout<<front->val<<endl;
Q.pop();
if(front->left){
cout<<front->left->val<<endl;
if(front->left->val>front->val) return false;
else Q.push(front->left);
}
if(front->right){
cout<<front->right->val<<endl;
if(front->right->val<front->val) return false;
else Q.push(front->right);
}
}
return true;

}


TreeNode* creatTree()//创建树
{
TreeNode *root=NULL;
int value;
cin>>value;
if(value==0) return root;
else{
root=(TreeNode*)malloc(sizeof(TreeNode));
root->val=value;
root->left=NULL;
root->right=NULL;
root->left=creatTree();
root->right=creatTree();
}
return root;
}


void preSearch(TreeNode * root)//递归先根遍历
{
if(root)
{
cout<<root->val<<"->";
preSearch(root->left);
preSearch(root->right);
}
}


void inSearch(TreeNode *root)//非递归中序
{
stack<TreeNode *> S;
if(root==NULL) exit(0);
TreeNode *p=root;

while(p||!S.empty())
{

while(p)
{
S.push(p);
p=p->left;
}
p=S.top();
S.pop();
cout<<p->val<<"->";
p=p->right;
}
}


void main()
{


TreeNode* root=creatTree();
preSearch(root);
cout<<endl;
inSearch(root);
cout<<check(root)<<endl;
cout<<getTreeLever(root,3);
}

0 0
原创粉丝点击