Java LeetCode篇-深入了解二叉树的经典解法(多种方式实现:构造二叉树)
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
// 方法1: 递归
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length);
}
private TreeNode helper(int[] nums, int start, int end) {
if (end - start <= 0) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, start, mid);
node.right = helper(nums, mid + 1, end);
return node;
}
// 方法2: 迭代
public TreeNode sortedArrayToBST2(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
TreeNode root = buildTree(nums, 0, nums.length);
return root;
}
private TreeNode buildTree(int[] nums, int start, int end) {
if (start >= end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = buildTree(nums, start, mid);
node.right = buildTree(nums, mid + 1, end);
return node;
}
}
这段代码提供了两种构建二叉搜索树的方法,分别是递归和迭代。递归方法更简洁易懂,而迭代方法在空间复杂度上可能更优。这两种方法都使用了数组作为输入,并且假设数组是有序的,然后构建一棵二叉搜索树。在实际应用中,我们可以根据具体情况选择合适的方法。
评论已关闭