最近有人问二叉树问题,这里写点文章记录一下。

如下二叉树,如何用java在代码里创建出来?
在这里插入图片描述
关注这方面的,大概都知道一个二叉树有前序、中序、后序,层序共4种遍历方法。
不清楚的看我的另一篇文章:二叉树的遍历

这里可以用一个数组把来表示上图二叉树:[1, 2, 0, 3, 4, 0, 0, 0, 5, 6, 0, 0, 7, 8, 9, 0, 0, 0, 0]

  1. 定义一个树的节点
public class TreeNode {
    public int data;
    public TreeNode leftChild;
    public TreeNode rightChild;
}
  1. 创建二叉树
public class CreateTree {

    static int i = 0;// 计数
    public static TreeNode createBinaryTree(int[] arr){
        if (arr == null || arr.length == 0) {
            return null;
        }
        TreeNode node = new TreeNode();
        if (i < arr.length) {// 如果二叉树数据空值正确,此判断可以省略
            node.data = arr[i++];
            if (node.data == 0) {
                return null;
            } else {
                node.leftChild = createBinaryTree(arr);
                node.rightChild = createBinaryTree(arr);
            }
        }
        return node;
    }

}
  1. 运行测试
    public static void main(String[] args) {
        // 二叉树的值保存在数组中,以0作为分隔,数字0表示空节点,数组
        int[] arr = new int[]{1, 2, 0, 3, 4, 0, 0, 0, 5, 6, 0, 0, 7, 8, 9, 0, 0, 0, 0};
        TreeNode binaryTree = createBinaryTree(arr);
        System.out.println(binaryTree);
    }

版权声明:本文为weixin_36939535原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_36939535/article/details/115910615