利用数组生成二叉树

import java.util.*;

public class BinaryTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode() {
        }
        public TreeNode(int val) {
            this.val = val;
        }
        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    
    public static TreeNode createTree() {
        Scanner sc = new Scanner(System.in);
        System.out.println("数组长度:");
        int length = sc.nextInt();

        //-1代表null
        System.out.println("数组值:");
        int[] arr = new int[length];
        for (int i = 0; i < length; i++) {
            arr[i] = sc.nextInt();
        }

        List<TreeNode> list = new ArrayList<>();
        for (int i : arr) {
            TreeNode node = null;
            if (i != -1) {
                node = new TreeNode(i);
            }
            list.add(node);
        }

        for (int i = 0; 2 * i + 2 < list.size(); i++) {
            if (list.get(i) != null) {
                list.get(i).left = list.get(2 * i + 1);
                list.get(i).right = list.get(2 * i + 2);
            }
        }
        
        //可以只生成奇数个节点,使得最后一个父节点必定存在右子节点,那么下面的处理可以省略
        int lastFather = (list.size() - 1 - 1) / 2;
        if (list.size() % 2 == 0) {
            list.get(lastFather).left = list.get(list.size() - 1);
        }
        
        return list.get(0);
    }

    public static void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                System.out.print(cur.val+"\t");
                cur = cur.right;
            }
        }
    }

    public static void main(String[] args) {
        traverse(createTree());
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值