[Leetcode 108]有序陣列轉二叉搜尋樹Convert Sorted Array to Binary Search Tree
阿新 • • 發佈:2018-11-13
【題目】
給出的升序排序的陣列,個數必為奇數,要求形成二叉搜尋(平衡)樹。
【思路】
輔助函式fun,[0,len]=>[0,mid-1]+[mid+1,len]。
當left>right,返回null。
public TreeNode fun(int[] nums,int left,int right) { int mid=(right+left)/2; TreeNode tmp=new TreeNode(nums[mid]); if(right<left) return null; tmp.left=fun(nums,left,mid-1); tmp.right=fun(nums,mid+1,right); return tmp; }
【AC程式碼】
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { publicTreeNode sortedArrayToBST(int[] nums) { int len=nums.length; if(nums.length==0){ return null; } TreeNode root=fun(nums,0,len-1); return root; } public TreeNode fun(int[] nums,int left,int right) { int mid=(right+left)/2; TreeNode tmp=new TreeNode(nums[mid]); if(right<left) return null; tmp.left=fun(nums,left,mid-1); tmp.right=fun(nums,mid+1,right); return tmp; } }