1. 程式人生 > >LeetCode--108. Convert Sorted Array to Binary Search Tree詳解

LeetCode--108. Convert Sorted Array to Binary Search Tree詳解

題目連結:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

題目要求將排序陣列轉為平衡二叉搜尋樹,先說一下二叉搜尋樹(Binary search tree)的定義和特性(wikipedia):

對應本題核心特點是:左子節點值小於等於父節點的值,右子節點大於父節點裡的值。再來看“平衡”,題目中也給出“a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every

 node never differ by more than 1”,而且LeetCode--110. Balanced Binary Tree就是要求判斷是否為平衡二叉樹。

講了這麼多前置知識,來談談思路,舉個例子看看:

                     

對應的平衡二叉搜尋樹是:

                                             

在OJ上驗證也是[-3,-8,6,-10,-6,0,7,null,-9,null,-4,null,5,null,8]就證明了我的一個思路:

對於排序(子)陣列A,起始索引i和終點索引j,mid=i+(j-i)/2就是當前樹的根節點root,然後A[i,mid-1]構成root的左子樹上,A[mid+1,j]構成root的右子樹,這是一個層層遞迴的過程,每個節點既是單個節點,也代表以自身為根節點的一個子樹。詳情看圖示:

這樣遞迴主體程式碼就寫出來了:

class Solution {
    
        public TreeNode sortedArrayToBST(int[] nums)
        {
            if(nums.length==0 || nums==null)
                return null;
            int i=0,j=nums.length-1;
            
            return recursive(nums,i,j);
        }
    
    public TreeNode recursive(int[] nums,int i,int j)
    {
        int mid=(j-i)/2+i;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=recursive(nums,i,mid-1);
        root.right=recursive(nums,mid+1,j);
        return root;
    }
}

其實最關鍵的就是寫出遞迴的終止條件:

這裡就是當i和j指向同一陣列元素或者無法對應陣列元素時需要return

if(i>j)
    return null;
if(i==j)
    return new TreeNode(nums[i]);

完整程式碼如下:

class Solution {
    
        public TreeNode sortedArrayToBST(int[] nums)
        {
            if(nums.length==0 || nums==null)
                return null;
            int i=0,j=nums.length-1;
            
            return recursive(nums,i,j);
        }
    
    public TreeNode recursive(int[] nums,int i,int j)
    {
        if(i>j)
            return null;
        if(i==j)
            return new TreeNode(nums[i]);
        int mid=(j-i)/2+i;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=recursive(nums,i,mid-1);
        root.right=recursive(nums,mid+1,j);
        return root;
    }
}