二叉树的构建与遍历

在介绍二叉树的篇章中,我们用方法简单创建了一个二叉树,如下代码: 

 public treeNode creattree(){
        treeNode A=new treeNode('A');
        treeNode B=new treeNode('B');
        treeNode C=new treeNode('C');
        treeNode D=new treeNode('D');
        treeNode E=new treeNode('E');
        treeNode F=new treeNode('F');
        A.left=B;
        A.right=C;
        B.left=D;
        C.left=E;
        C.right=F;
        return A;
    }

 但如果给定一个字符串,我们照上述代码写的话就多而复杂,有人问,创建一个二叉树不是最少含有一个中序遍历和前(后)序遍历才能唯一确定吗?下题给定‘#’为空树,那么我们只需要一个遍历结果即可构建一个唯一二叉树,题目如下:

题目链接二叉树遍历icon-default.png?t=O83Ahttps://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=60&&tqId=29483&rp=1&ru=/activity/oj&qru=/ta/tsing-kaoyan/question-ranking

题目要求

输入格式

输出格式

样例

解题代码

 思路:

        1、构建TreeNode类

        2、creatTree方法:创建根节点为空,如果第i个字符为#,则i++;否则创建val为第i个字符的根节点,接着以根节点左右子树为新子树继续构建节点

        3、编写中序遍历方法

import java.util.Scanner;

class TreeNode{
    public char val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(char val){
        this.val=val;
    }
}
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str=in.nextLine();
            TreeNode root=creatTree(str);
            inorder(root);
        }
    }
    public static int i=0;

    public static TreeNode creatTree(String str){
        TreeNode root=null;
        if(str.charAt(i)!='#'){
            root=new TreeNode(str.charAt(i));
            i++;
            root.left=creatTree(str);
            root.right=creatTree(str);  
        }else{
            i++;
        }
        return root;
    } 
    public static void inorder(TreeNode root){
        if(root==null){
            return;
        }
        inorder(root.left);
        System.out.printf(root.val+" ");
        inorder(root.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值