topic:
Given an array where elements are sorted into ascending order, convert it to a height balanced BST.
The following:
Given an array in which the array elements are sorted in descending order and converted to a balanced binary lookup tree. Algorithm Analysis:
First understand the concept binary lookup tree and the Balanced binary lookup tree:
The two-fork sort tree is either an empty tree or a two-fork tree with the following properties:
(1) If the left subtree is not empty, then the value of all nodes in the left subtree is less than the value of its root node; (2) If the right subtree is not empty, the value of all nodes in the right subtree is greater than or equal to the root node of the tree. (3) The left and right subtrees are also two-fork-sorted trees, and (4) There are no nodes with equal key values. The balanced binary tree (balanced Binary ) is also known as the AVL tree (unlike the AVL algorithm) and has the following properties:
(1) It is an empty tree or its left and right two subtrees the absolute value of the height difference is not more than 1,
(2) About two subtrees are a balanced binary tree.
* This is the problem of binary lookup tree, to convert an ordered array into a binary lookup tree.
* In essence, an array is equivalent to a binary lookup tree if it is viewed as a tree (that is, the midpoint is the root, the left and right of the left and the right subtrees).
* So if this tree is to be constructed, it is to convert the intermediate elements into roots and then recursively construct the left and right subtrees. So we're still using the binary tree recursive method, with the root as the return value,
* The recursive function of each layer takes the intermediate element as the current root and the node value, and then the left-right node is connected to the left and right interval recursive function return value. Time complexity or a tree traversal o (n),
* The total space complexity is the stack space O (logn) plus the result of the space O (n), the extra space is O (Logn), the overall is O (n).
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
* */Public
class Solution
{public
TreeNode sortedarraytobst (int[] nums)
{
if (nums= =null | | nums.length==0) return
null;
Return helper (nums,0,nums.length-1);
}
Private TreeNode Helper (int[] nums, int l, int r)
{
if (l>r) return
null;
int m = (l+r)/2;
TreeNode root = new TreeNode (nums[m]);
Root.left = Helper (nums,l,m-1);
Root.right = Helper (nums,m+1,r);
return root;
}
}