UVA 11234 ( 二叉树 前序 后续遍历方法)

Expressions

Font Size:

Arithmetic expressions are usually written with the operators in between the two operands (which is called infix notation). For example,(x+y)*(z-w) is an arithmetic expression in infix notation. However, it is easier to write a program to evaluate an expression if the expression is written in postfix notation (also known as reverse Polish notation). In postfix notation, an operator is written behind its two operands, which may be expressions themselves. For example,x y + z w - * is a postfix notation of the arithmetic expression given above. Note that in this case parentheses are not required.

To evaluate an expression written in postfix notation, an algorithm operating on a stack can be used. A stack is a data structure which supports two operations:

  1. push: a number is inserted at the top of the stack.
  2. pop: the number from the top of the stack is taken out.

During the evaluation, we process the expression from left to right. If we encounter a number, we push it onto the stack. If we encounter an operator, we pop the first two numbers from the stack, apply the operator on them, and push the result back onto the stack. More specifically, the following pseudocode shows how to handle the case when we encounter an operator O:

a := pop();b := pop();push(b O a);

The result of the expression will be left as the only number on the stack.

Now imagine that we use a queue instead of the stack. A queue also has a
push and pop operation, but their meaning is different:

  1. push: a number is inserted at the end of the queue.
  2. pop: the number from the front of the queue is taken out of the queue.

Can you rewrite the given expression such that the result of the algorithm using the queue is the same as the result of the original expression evaluated using the algorithm with the stack?

Input

The first line of the input contains a number T (T ≤ 200). The followingT lines each contain one expression in postfix notation. Arithmetic operators are represented by uppercase letters, numbers are represented by lowercase letters. You may assume that the length of each expression is less than10000 characters.

Output

For each given expression, print the expression with the equivalent result when using the algorithm with the queue instead of the stack. To make the solution unique, you are not allowed to assume that the operators are associative or commutative.

Sample Input

2
xyPzwIM
abcABdefgCDEF

Sample Output

wzyxIPM
gfCecbDdAaEBF


正常的表达式:树的中序遍历

逆波兰式:树的后序遍历

波兰式:树的前序遍历

根据这三个特性建树,层次遍历得到结果


#include<cstring>
#include<string>
#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstdlib>
#include<cmath>
#include<vector>
//#pragma comment(linker, "/STACK:1024000000,1024000000");

using namespace std;

#define maxn 45000
#define INF 0x3f3f3f3f

int u[maxn],v[maxn],fir[maxn],nex[maxn];
char s[maxn];
int st[maxn];
int top;
int e_max;

void init()
{
    memset(fir,-1,sizeof fir);
    e_max=0;
}

void add_edge(int s,int t)
{
    int e=e_max++;
    u[e]=s;
    v[e]=t;
    nex[e]=fir[s];
    fir[s]=e;
}

int que[maxn];
void bfs(int root)
{
    int l=0,r=-1;
    que[++r]=root;
    while(l<=r)
    {
        int p=que[l++];
        for(int i=fir[p];~i;i=nex[i])
        {
            que[++r]=v[i];
        }
    }
    for(int i=l-1;i>=0;i--)
    {
        printf("%c",s[que[i]]);
    }
    printf("\n");
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        init();
        top=-1;
        scanf("%s",s);
        int len=strlen(s);
        for(int i=0;i<len;i++)
        {
            if(s[i]>='a'&&s[i]<='z')
            {
                st[++top]=i;
            }
            else
            {
                int a=st[top--];
                int b=st[top--];
                add_edge(i,a);
                add_edge(i,b);
                st[++top]=i;
            }
        }
        int root=st[top--];
        bfs(root);
    }
    return 0;
}


### 二叉树前序和中序遍历推导后序遍历的算法 在二叉树遍历中,前序遍历(DLR)的顺序是:根节点 → 左子树 → 右子树,而中序遍历(LDR)的顺序是:左子树 → 根节点 → 右子树。通过前序和中序遍历结果,可以唯一地确定一棵二叉树的结构,并进一步推导出后序遍历(LRD)的结果。 #### 算法思想 1. **确定根节点**:前序遍历的第一个元素即为当前子树的根节点。 2. **划分左右子树**:在中序遍历中找到根节点,其左侧即为左子树的中序遍历结果,右侧即为右子树的中序遍历结果。 3. **递归构建子树**:根据左子树和右子树的长度,从前序遍历中划分出对应的左子树和右子树的前序遍历结果,并递归处理。 4. **后序遍历顺序**:在递归过程中,按照左子树 → 右子树 → 根节点的顺序将节点值加入结果列表。 #### 算法实现 以下是一个Python实现的示例代码: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree(preorder, inorder): if not preorder: return None root_val = preorder[0] root = TreeNode(root_val) root_index = inorder.index(root_val) left_inorder = inorder[:root_index] right_inorder = inorder[root_index+1:] left_size = len(left_inorder) right_size = len(right_inorder) left_preorder = preorder[1:1+left_size] right_preorder = preorder[1+left_size:] root.left = build_tree(left_preorder, left_inorder) root.right = build_tree(right_preorder, right_inorder) return root def postorder_traversal(root): result = [] def dfs(node): if not node: return dfs(node.left) dfs(node.right) result.append(node.val) dfs(root) return result # 示例输入 preorder = [1, 2, 3, 4, 5, 6, 7] inorder = [3, 2, 4, 1, 6, 5, 7] # 构建二叉树 root = build_tree(preorder, inorder) # 获取后序遍历结果 postorder = postorder_traversal(root) print("后序遍历结果:", postorder) # 输出: [3, 4, 2, 6, 7, 5, 1] ``` #### 算法分析 - **时间复杂度**:构建二叉树的时间复杂度为 $O(n^2)$,其中 $n$ 是节点数量。这是因为每次递归都需要在中序遍历中查找根节点的位置。可以通过使用哈希表优化查找,将时间复杂度降低到 $O(n)$。 - **空间复杂度**:递归调用栈的深度为 $O(n)$,因此空间复杂度为 $O(n)$。 #### 示例分析 以前序遍历 `preorder = [1, 2, 3, 4, 5, 6, 7]` 和中序遍历 `inorder = [3, 2, 4, 1, 6, 5, 7]` 为例: 1. 根节点为 `1`,在中序遍历中找到其位置,划分左子树 `inorder[:3] = [3, 2, 4]` 和右子树 `inorder[4:] = [6, 5, 7]`。 2. 左子树的前序遍历为 `preorder[1:4] = [2, 3, 4]`,右子树的前序遍历为 `preorder[4:] = [5, 6, 7]`。 3. 递归构建左子树和右子树,最终通过后序遍历得到结果 `[3, 4, 2, 6, 7, 5, 1]`[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值