Java根据Integer数组(有null值)递归构造二叉树
二叉树:
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
递归构造二叉树:
public static TreeNode creatTreeNode(Integer[] arr, int index) { if (index >= arr.length) { return null; } if (arr[index] == null) { return null; } TreeNode root = new TreeNode(arr[index]); root.left = creatTreeNode(arr, index * 2 + 1); root.right = creatTreeNode(arr, index * 2 + 2); return root; }