LintCode 把排序數組轉換為高度最小的二叉搜索樹

題目

給一個排序數組(從小到大),將其轉換為一棵高度最小的排序二叉樹。

樣例
給出數組[1,2,3,4,5,6,7], 返回

sortTree.PNG

分析

顯然這個問題可以用遞歸解決。
中間的節點總是在根節點,所以我們不停的找到中間節點即可,然后分別遞歸處理左子樹和右子樹即可

代碼

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param A: an integer array
     * @return: a tree node
     */
    public TreeNode sortedArrayToBST(int[] A) {  
        // write your code here
        if(A == null) return null;  
        TreeNode root = null;  
        return newTreeNode (root, A, 0, A.length-1); 
    }
    
    public TreeNode newTreeNode (TreeNode node, int[] A, int start, int end) {  
        if (start > end) {return null; }  
        //node = new TreeNode(0);  
        int mid = end - (end - start)/2;  
        node.val = A[mid];  
        node.left = newTreeNode(node.left, A, start, mid - 1);  
        node.right = newTreeNode(node.right, A, mid + 1, end);  
        return node;  
    } 
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容