Convert Sorted Array to Binary Search Tree 把一个有序数组转换成BST @LeetCode
2013-10-19 06:57
567 查看
题目:
给定一个有序的数组,要求转换为BST
思路:
递归。
每次找到数组中值作为BST的root,然后递归处理左半数组和右半数组分别作为左右子树
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return rec(num, 0, num.length-1);
}
public TreeNode rec(int[] num, int low, int high){
if(low > high){
return null;
}
int mid = low + (high-low)/2;
TreeNode root = new TreeNode(num[mid]);
root.left = rec(num, low, mid-1);
root.right = rec(num, mid+1, high);
return root;
}
}
给定一个有序的数组,要求转换为BST
思路:
递归。
每次找到数组中值作为BST的root,然后递归处理左半数组和右半数组分别作为左右子树
package Level2; import Utility.TreeNode; /** * Convert Sorted Array to Binary Search Tree * * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. */ public class S108 { public static void main(String[] args) { int[] num = {1,3}; TreeNode n = sortedArrayToBST(num); n.print(); } public static TreeNode sortedArrayToBST(int[] num) { return sortedArrayToBSTRec(num, 0, num.length-1); } // 二分查找节点值,并递归创建节点 private static TreeNode sortedArrayToBSTRec(int[] num, int low, int high){ if(low > high){ return null; } int mid = low + (high-low)/2; // 找到中值 TreeNode root = new TreeNode(num[mid]); // 创建根节点 root.left = sortedArrayToBSTRec(num, low, mid-1); // 递归创建左子树和右子树 root.right = sortedArrayToBSTRec(num, mid+1, high); return root; } }
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return rec(num, 0, num.length-1);
}
public TreeNode rec(int[] num, int low, int high){
if(low > high){
return null;
}
int mid = low + (high-low)/2;
TreeNode root = new TreeNode(num[mid]);
root.left = rec(num, low, mid-1);
root.right = rec(num, mid+1, high);
return root;
}
}
相关文章推荐
- Java基础(十二)——IO流
- HTML5中input属性在JSP中的使用
- svn常用指令
- 一颗小行星掠过地球附近
- JSP中form标签的使用
- MillionDollarHomePage.com:100万美元的网页
- How to use JPA from a JBoss Web application ?(jboss 中如何使用线程安全的EntityManagerFactory )
- Tor 介绍
- 递归转非递归理解
- ImageUtils工具演示
- 递归,回溯,DFS,BFS的理解和模板
- 灯光上网"技术江苏已实现 仍难取代无线宽带
- [LeetCode] Populating Next RIght Pointer in Each Node II
- 在Ubuntu 12.04上安装GNOME实现XRDP远程桌面访问ubuntu
- Linux下配置DNS
- request.getRequestDispatcher().forward(request,response)和response.sendRedirect()的区别
- 『设计』Slithice 分布式架构设计-支持一体式开发,分布式发布
- 『设计』Slithice 分布式架构设计-支持一体式开发,分布式发布
- Path Sum II 二叉树路径和,打印所有路径 @LeetCode
- mysql主从复制(超简单)