ACM模式下二叉树的构建以及三种遍历方式

题目链接

题目页面 (kamacoder.com)

题目描述

题目描述

给出一个n个节点的二叉树,请求出二叉树的前序遍历,中序遍历和后序遍历。

输入描述

      第一位一个整数n,第二个表示右儿子序号,如果该序号为0表示没有。 (例如下面示例中,F序号为1,C序号为2,E序号为3,A序号为4,D序号为5,G序号为6,B序号为7)

输出描述

       共三行,第一行为二叉树的前序遍历,第二行为中序遍历,第三行为后序遍历

输入示例

7
F 2 3
C 4 5
E 0 6
A 0 0
D 7 0
G 0 0
B 0 0

输出示例 

FCADBEG
ACBDFEG
ABDCGEF

算法示例

import java.util.Scanner;
public class Main{
    public static class TreeNode{
        String val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(String val){
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }
    public static void main (String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        if(n == 0)  return;
        String[][] arr = new String[n + 1][3];
        for(int i = 1; i <= n; i++){
            String[] temp = sc.nextLine().split(" ");
            arr[i][0] = temp[0];
            arr[i][1] = temp[1];
            arr[i][2] = temp[2];
        }
        // 构造二叉树
        TreeNode root = new TreeNode(arr[1][0]);
        getTree(root, arr, 1);
        prevPrint(root);
        System.out.println();
        midPrint(root);
        System.out.println();
        backPrint(root);
    }
    public static void getTree(TreeNode root, String[][] str, int idx){
        int L = Integer.parseInt(str[idx][1]);
        int R = Integer.parseInt(str[idx][2]);
        if(L != 0){
            TreeNode cur = new TreeNode(str[L][0]);
            root.left = cur;
            getTree(cur, str, L);
        }
        if(R != 0){
            TreeNode cur = new TreeNode(str[R][0]);
            root.right = cur;
            getTree(cur, str, R);
        }
    }
    public static void prevPrint(TreeNode root){
        if(root == null)    return;
        System.out.print(root.val);
        prevPrint(root.left);
        prevPrint(root.right);
    }
    public static void midPrint(TreeNode root){
        if(root == null)    return;
        midPrint(root.left);
        System.out.print(root.val);
        midPrint(root.right);
    }
    public static void backPrint(TreeNode root){
        if(root == null)    return;
        backPrint(root.left);
        backPrint(root.right);
        System.out.print(root.val);
    }
}

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值