Java 根据已有的字符串(前序遍历的字符串已告知)创建一颗二叉树,并输出该树的中序遍历和后序遍历

代码中的二叉树长这个样子↓↓↓
在这里插入图片描述

import java.util.Scanner;
import java.util.Stack;

public class Build {
    private static class Node {
        char val;
        Node left;
        Node right;

        public Node(char val) {
            this.val = val;
        }
    }
    //根据已有的字符串(前序遍历的字符串已告知)创建一颗二叉树
    public static int i=0;
    public static Node buildTree(String str) {
        Node root=null;
        if(str.charAt(i)!='#'){ //在不用定义数组的前提下,用该方法str.charAt(i)获取当前下标所对应的字符
            root=new Node(str.charAt(i));//相当于是把字符值封装到一个结点,赋给root
            i++;
            root.left=buildTree(str);
            root.right=buildTree(str);
        }else{
            i++;
        }
        return root;
    }
    //中序遍历:
    public static void inOrderTraversalNor(Node root) {
        if (root == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        Node cur = root;
        while (cur != null||!stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            Node top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }
    //后序遍历
    public static void postOrderTraversalNor(Node root){
        if (root == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        Node cur = root;
        Node prev=null; //定义了一个前驱结点是为了防止重复打印
        while (cur != null||!stack.empty()) {
            while(cur!=null){
                stack.push(cur);//当cur不为空时,就将该结点及该结点的左边入栈,如此循环,直到把最左边的全部入栈
                cur=cur.left;
            }
            cur=stack.peek();//取当前栈顶元素
            if(cur.right==null||cur.right==prev){  //判断当前栈顶元素右孩子为空的情况,这样可直接打印当前栈顶元素
                System.out.printf(cur.val+" ");
                stack.pop();
                prev=cur;
                cur=null;
            }else{//若当前栈顶元素的右孩子不为空,
                cur=cur.right;
            }
        }
    }
    /*public static void main(String[] args) {
        Node root=buildTree("ABC##DE#G##F###");

        System.out.printf("中序遍历:");
        inOrderTraversalNor(root);
        System.out.println();

        System.out.printf("后序遍历:");
        postOrderTraversalNor(root);
        System.out.println();
    }*/
    //还有一种是需要自己去输入字符串的
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        while(input.hasNext()){
            String str=input.nextLine();
            Node root=buildTree(str);

            inOrderTraversalNor(root);
            System.out.println();
            postOrderTraversalNor(root);
        }
    }
}

执行结果:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值