博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode - Convert Sorted Array to Binary Search Tree
阅读量:4685 次
发布时间:2019-06-09

本文共 1163 字,大约阅读时间需要 3 分钟。

leetcode - Convert Sorted Array to Binary Search Tree

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

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* sortedArrayToBST(vector
& nums) { if(nums.size() == 0) return NULL; int mid = nums[nums.size()/2]; int i = 0; TreeNode* root = new TreeNode(mid); root->left = toBST(nums, 0, nums.size()/2 - 1); root->right = toBST(nums, nums.size()/2+1, nums.size()-1); return root; } TreeNode* toBST(vector
& nums, int begin, int end){ if(begin > end) return NULL; int mid = nums[(begin+end)/2]; TreeNode* root = new TreeNode(mid); root->left = toBST(nums, begin, (begin+end)/2 - 1); root->right = toBST(nums, (begin+end)/2+1, end); return root; }};

将一个升序数组建立一个高度平衡的二叉查找树。 如果高度平衡,则根节点一定是中间的数。用递归。

转载于:https://www.cnblogs.com/shnj/p/4749317.html

你可能感兴趣的文章
git的介绍和配置
查看>>
团队项目 进展
查看>>
简单的NHibernate helper类,支持同一事务的批量数据处理
查看>>
导出数据库指定表所有数据
查看>>
C 语言 习题 1-14
查看>>
密码锁
查看>>
AVL树-查找-插入
查看>>
Codeforces 600E Lomsat gelral(dsu on tree)
查看>>
值类型和引用类型区别,一看就懂
查看>>
UVa 11375 Matches
查看>>
JdbcTemplate
查看>>
leetcode 2. 两数相加(Add Two Numbers)
查看>>
Crimm Imageshop 2.0 发布。
查看>>
分页存储过程
查看>>
不可忽略的知识点
查看>>
Xcode中修改默认文件头部注释
查看>>
从一个针对ASP.NET MVC框架的Controller.Action的请求处理顺序来说整个请求过程。
查看>>
[ZJOI2011]营救皮卡丘
查看>>
首页列表显示全部问答,完成问答详情页布局。
查看>>
pandas read excel文件碰到的一个小问题
查看>>