二叉树的创建

本文介绍两种使用Java实现的二叉树创建方法:递归创建与非递归创建(双栈实现)。输入为二叉树先序遍历的字符串形式,其中空节点用'#'表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录下几种创建二叉树的方法,仅java实现。
二叉树结构定义为:

    public class Node {
        char val;
        Node left;
        Node right;

        public Node(){}

        public Node(int val) {
            this.val = val;
        }
    }

输入为一组二叉树先序遍历顺序的字符串(结点元素字符非‘#’、空格、回车),其中空结点都用 # 符号表示。
例如二叉树:
               1
            /      \
          2         3
      /       \     /
     4        5  6
      \       /
       7    8
               \
                9
输入示例为:124#7##58#9###36###

递归创建


public class TreeCreator {
    private static List<Character> chs = new ArrayList<>();
    private static Iterator<Character> it = null;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine().trim();
        for (int i = 0; i < s.length(); i++) {
            chs.add(s.charAt(i));
        }
        it = chs.iterator();
        Node root = generateTree();
        sc.close();
    }

    /**
     * 读入字符串为先序遍历,空结点都用#表示
     */
    private static Node generateTree() {
        Node root = null;
        if(!it.hasNext()) return null;
        char c = it.next();
        if (c != '#') {
            root = new Node(c);
            root.left = generateTree();
            root.right = generateTree();
        }
        return root;
    }

非递归创建


    /**
     * 非递归实现,使用双栈
     * @return
     */
    public static Node generateTree(String s) {
        if (s == null || s.trim().equals("")) return null;
        // 第一个字符必须非“#”
        Node root = new Node(s.charAt(0));
        Stack<Node> nodes = new Stack<>();
        Stack<Integer> tag = new Stack<>();
        nodes.push(root);
        tag.push(0);
        for (int i = 1; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '#') {
                while (!tag.isEmpty() && tag.peek() == 1) {
                    tag.pop();
                    nodes.pop();
                }
                if (!tag.isEmpty()) {
                    tag.pop();
                    tag.push(1);
                }
            } else {
                Node node = new Node(c);
                if (!nodes.isEmpty()) {
                    Node head = nodes.peek();
                    if (head.left != null || tag.peek() == 1) {
                        head.right = node;
                    } else {
                        head.left = node;
                    }
                }
                nodes.push(node);
                tag.push(0);
            }
        }
        return root;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值