LeetCode -- Convert Sorted Array to Binary Search Tree
2015-10-17 00:37
369 查看
题目描述:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
就是对一个排序的序列生成高度平衡的二叉树。
思路:
本题的算法思路属于分治。
即在数组nums取中间元素nums[m]并生成节点添加到树上,然后对左右分别做DFS。即使用m左边元素生成左子树,使用m右边元素生成右子树。
实现代码:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
就是对一个排序的序列生成高度平衡的二叉树。
思路:
本题的算法思路属于分治。
即在数组nums取中间元素nums[m]并生成节点添加到树上,然后对左右分别做DFS。即使用m左边元素生成左子树,使用m右边元素生成右子树。
实现代码:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode SortedArrayToBST(int[] nums) { if(nums == null || nums.Length == 0){ return null; } var node = new TreeNode(nums[nums.Length/2]); BuildTree(nums, 0, nums.Length - 1, ref node); return node; } private void BuildTree(int[] nums,int start, int end, ref TreeNode current) { if(start > end){ return ; } var m = (start + end) / 2; current = new TreeNode(nums[m]); if(start == end){ return; } BuildTree(nums, start, m - 1, ref current.left); BuildTree(nums, m + 1, end, ref current.right); } }
相关文章推荐
- json格式化
- LeetCode -- Climbing Stairs
- LeetCode -- Binary Tree Preorder Traversal
- 浅谈R语言
- Scala学习笔记26【Set、Map、TreeSet、TreeMap实战】
- seo
- 有关页面编码的控制问题,乱码如何解决
- LeetCode -- Best Time to Buy and Sell Stock
- 两部分代码比较,所带来的问题,下面已解决
- Android四大组件-BroadcastReceiver
- 【译】理解Spring MVC Model Attribute 和 Session Attribute
- market排名-wp
- LeetCode -- Validate Binary Search Tree
- IOS正则表达式,很详细,值得一看!
- 新产品技术节点--TR1--TR6
- Android深度自定义Dialog对话框
- Parameter System
- 物流表结构
- 字节序、比特序(一)
- MySQL索引实验-主键索引一定比辅助索引快吗?