public static void main(String[] args) {
Integer[] levelOrderTraversal = {3, 9, 20, null, null, 15, 7};
// Replace nulls with Integer.MIN_VALUE to handle null values in the array
TreeNode test = new Solution().buildTree(levelOrderTraversal);
System.out.println("");
}
public TreeNode buildTree(Integer[] levelOrderTraversal) {
if (levelOrderTraversal == null || levelOrderTraversal.length == 0) {
return null;
}
TreeNode root = new TreeNode(levelOrderTraversal[0]);
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int i = 1;
while (!queue.isEmpty() && i < levelOrderTraversal.length) {
TreeNode current = queue.poll();
// Process left child
if (i < levelOrderTraversal.length && levelOrderTraversal[i] != null) {
current.left = new TreeNode(levelOrderTraversal[i]);
queue.offer(current.left);
}
i++;
// Process right child
if (i < levelOrderTraversal.length && levelOrderTraversal[i] != null) {
current.right = new TreeNode(levelOrderTraversal[i]);
queue.offer(current.right);
}
i++;
}
return root;
}
leetcode上题目构建二叉树作为输入代码(层序遍历)
最新推荐文章于 2024-09-03 18:29:17 发布