寻找切割点,分割点为当前节点,然后递归左区间和右区间
1、确定返回值以及参数
返回值:需要用递归的返回值来构造节点的左右孩子
参数:传入数组,左下标和右下标用来操作数组
定义左闭右闭区间,分割过程也坚持左闭右闭
2、递归终止条件
区间left>right的时候,是空节点
3、单层递归逻辑
(1)取了中间位置int mid = left + (right - left) / 2;
开始以中间位置的元素构造节点 TreeNode root = new TreeNode(nums[mid]);
(2)接着划分区间,root的左孩子接住下一层左区间的构造节点,右孩子接触下一层右孩子构造的节点
(3)最后返回root节点
class Solution { public TreeNode sortedArrayToBST(int[] nums) { TreeNode root = traversal(nums, 0, nums.length - 1); return root; } // 左闭右闭区间[left, right) private TreeNode traversal(int[] nums, int left, int right) { if (left > right) return null; int mid = left + ((right - left) / 2); TreeNode root = new TreeNode(nums[mid]); root.left = traversal(nums, left, mid - 1); root.right = traversal(nums, mid + 1, right); return root; }
迭代
class Solution { public TreeNode sortedArrayToBST(int[] nums) { if (nums.length == 0) return null; //根节点初始化 TreeNode root = new TreeNode(-1); Queue<TreeNode> nodeQueue = new LinkedList<>(); Queue<Integer> leftQueue = new LinkedList<>(); Queue<Integer> rightQueue = new LinkedList<>(); // 根节点入队列 nodeQueue.offer(root); // 0为左区间下表初始位置 leftQueue.offer(0); // nums.size() - 1为右区间下表初始位置 rightQueue.offer(nums.length - 1); while (!nodeQueue.isEmpty()) { TreeNode currNode = nodeQueue.poll(); int left = leftQueue.poll(); int right = rightQueue.poll(); int mid = left + ((right - left) >> 1); // 将mid对应的元素给中间节点 currNode.val = nums[mid]; // 处理左区间 if (left <= mid - 1) { currNode.left = new TreeNode(-1); nodeQueue.offer(currNode.left); leftQueue.offer(left); rightQueue.offer(mid - 1); } // 处理右区间 if (right >= mid + 1) { currNode.right = new TreeNode(-1); nodeQueue.offer(currNode.right); leftQueue.offer(mid + 1); rightQueue.offer(right); } } return root; } }