标签:
Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.
Given [1,2,3,4,5,6,7]
, return
4
/ 2 6
/ \ / 1 3 5 7
分析:
这是一道非常明显的递归题。取array的中间数作为树的root,array 左边部分是左子树部分,array右边部分是右子树部分。
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param A: an integer array 15 * @return: a tree node 16 * cnblogs.com/beiyeqingteng/ 17 */ 18 public TreeNode sortedArrayToBST(int[] A) { 19 if (A == null || A.length == 0) return null; 20 return helper(A, 0, A.length - 1); 21 } 22 23 public TreeNode helper(int[] A, int i, int j) { 24 if (i == j) { 25 return new TreeNode(A[i]); 26 } else if (i > j) { 27 return null; 28 } else { 29 int mid = i + (j - i) / 2; 30 TreeNode root = new TreeNode(A[mid]); 31 root.left = helper(A, i, mid - 1); 32 root.right = helper(A, mid + 1, j); 33 return root; 34 } 35 } 36 }
转载请注明出处:cnblogs.com/beiyeqingteng/
Convert Sorted Array to Binary Search Tree With Minimal Height
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631738.html