The Problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Notes:
- BST is left node left less than parent then less than right. As the input array is in ascending order, in each recursion , take the middle element as parent, first half start a branch to construct left child, latter half start another branch to construct right child.
Java Solution
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] num) { int len = num.length; if(len==0) return null; return constructTree(num, 0, len-1); } private TreeNode constructTree(int[] num, int start, int end){ if(start > end) return null; int mid = (start+end)/2; TreeNode parent = new TreeNode(num[mid]); parent.left = constructTree(num, start, mid-1); parent.right = constructTree(num, mid+1, end); return parent; } }
Advertisements
Pingback: Leetcode–Convert Sorted List to Binary Search Tree | Linchi is coding