Tree 二叉树的建立 和遍历

http://acm.nyist.net/JudgeOnline/problem.php?pid=221
Tree
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述 
Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes.
This is an example of one of her creations: 
                                                D

                                              / \

                                             /   \

                                            B     E

                                           / \     \

                                          /   \     \

                                         A     C     G

                                                    /

                                                   /

                                                  F

To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. 
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).

Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree.
However, doing the reconstruction by hand, soon turned out to be tedious. 
So now she asks you to write a program that does the job for her! 
输入
The input will contain one or more test cases. 
Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)
Input is terminated by end of file. 
输出
For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
题意:利用二叉树的先序遍历和中序遍历建立二叉树 并输出二叉树的后序遍历
解析:
建立二叉树首先建立节点类
typedef struct node//定义结点
{
    char data;
    struct node *lchild,*rchild;
} Node,*BitTree;
利用先序和中序建立树 可以用递归的方法
每次找出先序遍历中各点在中序中的位置
int search(char ino[],char c)//在中序序列中查找先序中该元素所在位置
{
    int i=0;
    while(ino[i]!=c&&ino[i])  i++;
    if(ino[i]==c)   return i;
}

如果在开始的位置则左子树为空 在最右边则右子树为空 在中间位置的话 则又分成两块 继续递归
void CrtBT(BitTree &T,char pre[],char ino[],int ps,int is,int n)/*递归算法构造函数,建立二叉链表*/
{
    int k;
    if(n==0)  T=NULL;
    else
    {
        k=search(ino,pre[ps]);//找到在中序中的位置  分为两部分继续递归
        T=(BitTree)malloc(sizeof(Node));
        T->data=pre[ps];
        if(k==is)     T->lchild=NULL;//如果中序中 字符左为空的话  左子树即为空
        //先序前进一个  中序不变  字符程度为总长度 k减去  is  既 左边剩下的个数
        else     CrtBT(T->lchild,pre,ino,ps+1,is,k-is);//
        if(k==is+n-1)     T->rchild=NULL;
        //同理
        else     CrtBT(T->rchild,pre,ino,ps+1+(k-is),k+1,n-(k-is)-1);
    }
}

后续遍历比较简单了
void PostOrder(BitTree T)
{
    if(T)
    {
        PostOrder(T->lchild);
        PostOrder(T->rchild);
        printf("%c",T->data);
    }
}

整个代码为
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#define size 100
typedef struct node//定义结点
{
    char data;
    struct node *lchild,*rchild;
} Node,*BitTree;
int search(char ino[],char c)//在中序序列中查找先序中该元素所在位置
{
    int i=0;
    while(ino[i]!=c&&ino[i])  i++;
    if(ino[i]==c)   return i;
}
void CrtBT(BitTree &T,char pre[],char ino[],int ps,int is,int n)/*递归算法构造函数,建立二叉链表*/
{
    int k;
    if(n==0)  T=NULL;
    else
    {
        k=search(ino,pre[ps]);//找到在中序中的位置  分为两部分继续递归
        T=(BitTree)malloc(sizeof(Node));
        T->data=pre[ps];
        if(k==is)     T->lchild=NULL;//如果中序中 字符左为空的话  左子树即为空
        //先序前进一个  中序不变  字符程度为总长度 k减去  is  既 左边剩下的个数
        else     CrtBT(T->lchild,pre,ino,ps+1,is,k-is);//
        if(k==is+n-1)     T->rchild=NULL;
        //同理
        else     CrtBT(T->rchild,pre,ino,ps+1+(k-is),k+1,n-(k-is)-1);
    }
}
void PostOrder(BitTree T)
{
    if(T)
    {
        PostOrder(T->lchild);
        PostOrder(T->rchild);
        printf("%c",T->data);
    }
}
int main()
{
    char pre[size],ino[size];
    while(scanf("%s%s",pre,ino)!=EOF)
    {
        BitTree T=NULL;
        CrtBT(T,pre,ino,0,0,strlen(pre));
        PostOrder(T);
        printf("\n");
    }
}



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
当然,我可以为你提供二叉树建立遍历代码以及注释。以下是示例代码: ```python # 定义二叉树节点类 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 二叉树建立 def buildTree(preorder, inorder): # 利用前序遍历和中序遍历序列构造二叉树 if not preorder or not inorder: return None root = TreeNode(preorder[0]) idx = inorder.index(preorder[0]) root.left = buildTree(preorder[1:idx+1], inorder[:idx]) root.right = buildTree(preorder[idx+1:], inorder[idx+1:]) return root # 二叉树前序遍历 def preorderTraversal(root): res = [] if root: res.append(root.val) res += preorderTraversal(root.left) res += preorderTraversal(root.right) return res # 二叉树中序遍历 def inorderTraversal(root): res = [] if root: res += inorderTraversal(root.left) res.append(root.val) res += inorderTraversal(root.right) return res # 二叉树后序遍历 def postorderTraversal(root): res = [] if root: res += postorderTraversal(root.left) res += postorderTraversal(root.right) res.append(root.val) return res ``` 注释说明: 1. `TreeNode` 类表示二叉树的节点,包括节点值 `val`,左子树 `left` 和右子树 `right`。 2. `buildTree` 函数利用前序遍历序列和中序遍历序列构造二叉树,返回根节点。 3. `preorderTraversal` 函数实现二叉树的前序遍历,返回遍历结果。 4. `inorderTraversal` 函数实现二叉树的中序遍历,返回遍历结果。 5. `postorderTraversal` 函数实现二叉树的后序遍历,返回遍历结果。 以上代码适用于 Python 语言,其他语言的实现方式类似。希望能够对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值