逆序路径

23 篇文章 0 订阅

Problem Description

设有一二叉树,其节点值为字符型并假设各值互不相等,采用顺序存储结构存储,空二叉树用'#'表示。现要求设计一个算法,逆序输出从根到层序编号为i的结点的路径。如有一棵二叉树顺序存储为A#B###C#######D,则从根到层序编号为15的逆路径为DCBA。
 

 Input

有多组数据,每组测试数据有两行,第一行为数组元素个数n(n<=50)和结点的层序编号m(m>0),第二行为数组各元素。

 Output

若编号m所对应的结点有效,则逆序输出从根到该点的路径;若无效,则输出"data error"。

 Sample Input

15 7
A#B###C#######D
13 5
ABC#DE###F##G

 Sample Output

CBA
DBA
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;


typedef struct BiNode {

    char data;
    struct BiNode* rchild,*lchild;


} BiNode,*BiTree;

void  ToTree(BiTree& bt,char* str,int start,int len) {
    if(str[start]=='#'||start>=len) {
        bt=NULL;
    } else {
        bt=new BiNode;
        bt->data=str[start];
        ToTree(bt->lchild,str,start*2+1,len);
        ToTree(bt->rchild,str,start*2+2,len);
    }
}

void PreOrder(BiTree root) {

    if(root) {
        cout<<root->data;
        PreOrder(root->lchild);
        PreOrder(root->rchild);
    }

}


class Stack {
private:
    int top;
    char data[51];
public:
    Stack() {
        top=-1;
    }
    void Push(char ch) {

        data[++top]=ch;
    }
    char Pop() {
        if(top!=-1) {
            return data[top--];
        }
        return '#';

    }
    void PrintStack() {

        while(top!=-1) {
            char ret=Pop();
            cout<<ret;
        }
        cout<<endl;
    }

};


void Path(BiTree bt,char ch,Stack& s) {

    if(bt) {
        s.Push(bt->data);
        if(bt->data==ch) {
            s.PrintStack();
        } else {
            Path(bt->lchild,ch,s);
            Path(bt->rchild,ch,s);
        }
        s.Pop();
    }

}

int main() {

   
    int n,m;
    while(cin>>n>>m) {
        char str[51];
        cin>>str;
        char ch='#';
        int len=strlen(str);
        for(int i=0; i<len; i++) {
            if(i==m-1) {
                ch=str[i];
            }
        }

        if(ch=='#') {
            cout<<"data error"<<endl;
        } else {
            BiTree root;
            ToTree(root,str,0,n);
            Stack s;
            Path(root,ch,s);
            //   PreOrder(root);
        }
    }
    return 0;
}

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值