LeetCode刷題Easy篇Convert Sorted Array to Binary Search Tree
阿新 • • 發佈:2018-12-05
題目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, 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.
Example:
Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
簡單說就是把一個有序陣列轉為平衡二叉樹。常見的二叉查詢樹,有可能退化為連結串列,時間複雜度從logn將退化為O(n),所以實際應用中的AVL,紅黑樹都是平衡二叉樹
我的嘗試
其實是構造一個平衡二叉樹,無非是節點值已經指定,沒有思路處理這類問題,看了disscuss之後,按照高手的思路自己寫了一下,看看是否可以一點就通。
先梳理一下思路,二叉平衡時,首先滿足二叉樹的條件,左側小於根節點,右側大於根節點。因為陣列有序,其實我們尋找中間的節點作為根節點就可以。如何保證平衡呢?每次都是中間元素作為根節點,所有左右節點數相差絕對值不會大於1.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length==0) return null; int p=0; int q=nums.length; return createTree(nums,p,q); } public TreeNode createTree(int[] nums,int p,int q){ if(p>q){ return null; } int mid=(p+q)/2; TreeNode treeNode=new TreeNode(nums[mid]); treeNode.left=createTree(nums,0,mid-1); treeNode.right=createTree(nums,mid+1,nums.length); return treeNode; } }
執行之後stackoverflow錯誤。遞迴呼叫createTree的入參寫錯了,修改後如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length==0) return null; int p=0; int q=nums.length-1; return createTree(nums,p,q); } public TreeNode createTree(int[] nums,int p,int q){ if(p>q){ return null; } int mid=(p+q)/2; TreeNode treeNode=new TreeNode(nums[mid]); treeNode.left=createTree(nums,p,mid-1); treeNode.right=createTree(nums,mid+1,q); return treeNode; } }