Topic:
Converts an ordered array in ascending order to a highly balanced binary search tree.
In this problem, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9], a workable answer is: [0,-3,9,-10,null,5], which can be represented as the following highly balanced binary search tree: 0 / -3 9 / /-10 5
Idea: Using dichotomy to create a balanced binary tree, the root node is just the middle of the node, the root of the left subtree of the tree is the middle node of the left part of the array, the right subtree of the root node is the middle node of the right part of the data; The code execution results and examples give different results, but satisfy the balanced binary tree.
Code:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */class Solution {public TreeNode sortedarraytobst (int[] nums) { if (nums = = NULL | | nums.length = = 0) return null; Return Gettree (nums,0,nums.length-1); } Public TreeNode gettree (int []nums,int l,int r) { if (L <= r) { int mid = (l+r)/2; TreeNode node = new TreeNode (Nums[mid]); Node.left = Gettree (nums,l,mid-1); Node.right = Gettree (nums,mid+1,r); return node; } else{ return null;}} }
Leetcode converting an ordered array to a two-fork search tree