树对象
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
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 class TreeNodeUtil {
public static TreeNode arrayToTreeNode(Integer[] array) {
if (array.length == 0) {
return null;
}
TreeNode root = new TreeNode(array[0]);
Queue queue = new LinkedList<>();
queue.add(root);
boolean isLeft = true;
for (int i = 1; i < array.length; i++) {
TreeNode node = (TreeNode) queue.peek();
if (isLeft) {
if (array[i] != null) {
node.left = new TreeNode(array[i]);
queue.offer(node.left);
}
isLeft = false;
} else {
if (array[i] != null) {
node.right = new TreeNode(array[i]);
queue.offer(node.right);
}
queue.poll();
isLeft = true;
}
}
return root;
}
}
使用例子
public static void main(String[] args) {
Integer[] arr = new Integer[]{3,2,3,null,3,null,1};
TreeNode treeNode = TreeNodeUtil.arrayToTreeNode(arr);
}