144-12

发布时间 2023-10-12 21:06:55作者: 依然范德BIAO

在二叉树中查找值为x的结点,找出该结点所有的祖宗结点,值为x的结点个数不多于1个

利用二叉树的后序非递归遍历,在Pop函数后判断是否结点值是否等于x,若等于,栈中全是x的祖宗结点,依次弹出

#include <stdio.h>
#include <stdlib.h>

#define MaxSize 100

typedef struct node{
    int data;
    struct node *lchild,*rchild;
}TreeNode,*Tree;

typedef TreeNode* Elem;

typedef struct{
    Elem data[MaxSize];
    int top;
}Stack;

void InitStack(Stack &S)
{
    S.top=-1;
}

bool isEmpty(Stack S)
{
    if(S.top==-1)
        return true;
    else
        return false;
}

bool isFull(Stack S)
{
    if(S.top==MaxSize-1)
        return true;
    else
        return false;
}

bool Push(Stack &S,Elem p)
{
    if(isFull(S))
        return false;
    S.data[++S.top]=p;
    return true;
}

bool Pop(Stack &S,Elem &p)
{
    if(isEmpty(S))
        return false;
    p=S.data[S.top--];
    return true;
}

bool GetTop(Stack S,Elem &p)
{
    if(isEmpty(S))
        return false;
    p=S.data[S.top];
    return true;
}

void CreateTree(Tree &T)
{
    int x;
    scanf("%d",&x);
    if(x==-1)
    {
        T=NULL;
        return;
    }
    else
    {
        T=(TreeNode*)malloc(sizeof(TreeNode));
        T->data=x;
        printf("输入%d的左结点:",x);
        CreateTree(T->lchild);
        printf("输入%d的右结点:",x);
        CreateTree(T->rchild);
    }
}

void Select(Tree T,int x)
{
    Stack S;
    InitStack(S);
    TreeNode *p=T;
    TreeNode *r=NULL;
    while(p || !isEmpty(S))
    {            
        if(p)
        {
            Push(S,p);
            p=p->lchild;
        }
        else
        {
            GetTop(S,p);
            if(p->rchild&&p->rchild!=r)
                p=p->rchild;
            else
            {
                Pop(S,p);
                if(p->data==x)
                {
                    printf("%d的祖宗结点是:",x);
                    while(!isEmpty(S))
                    {
                        Pop(S,p);
                        printf("%d  ",p->data);
                    }
                    return;    
                }    
                r=p;
                p=NULL;
            }
        }
    }
    printf("树T中不存在值等于%d的结点",x);
}

int main()
{
    Tree T;
    CreateTree(T);
    Select(T,0);
    return 0;
}