Convert Sorted Array to Binary Search Tree leetcode java


題目

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

題解

先復習下什么是二叉搜索樹(引自Wikipedia):

二叉查找樹Binary Search Tree),也稱有序二叉樹(ordered binary tree),排序二叉樹(sorted binary tree),是指一棵空樹或者具有下列性質的二叉樹

  1. 若任意節點的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
  2. 任意節點的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
  3. 任意節點的左、右子樹也分別為二叉查找樹。

 

 

再復習下什么是平衡二叉樹(引自GeekforGeek):

An empty tree is height-balanced. A non-empty binary tree T is balanced if:
   1) Left subtree of T is balanced
   2) Right subtree of T is balanced
   3) The difference between heights of left subtree and right subtree is not more than 1. 

 

解決方法是選中點構造根節點,然后遞歸的構造左子樹和右子樹。

代碼如下:

 1      public TreeNode buildTree( int[] num,  int low,  int high){
 2          if(low>high)
 3              return  null;
 4         
 5          int mid = (low+high)/2;
 6         TreeNode node =  new TreeNode(num[mid]);
 7         node.left = buildTree(num,low,mid-1);
 8         node.right = buildTree(num,mid+1,high);
 9          return node;
10     }
11      public TreeNode sortedArrayToBST( int[] num) {
12         return buildTree(num,0,num.length-1);
13     }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM