Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
public TreeNode sortedArrayToBST(int[] num) { if(num.length==0) return null; return toBST(num, 0, num.length-1); } private TreeNode toBST(int[] num, int start, int end) { if(start > end) { return null; } int m = (start+end)>>1; TreeNode node = new TreeNode(num[m]); node.left = toBST(num, start, m-1); node.right = toBST(num, m+1, end); return node; }
TreeNode* sortedArrayToBST(vector<int>& nums) { if(!nums.size()) return NULL; int *arr = &nums[0]; return toBST(arr, nums.size()); } TreeNode *toBST(int* nums, int n) { if(n == 0) return NULL; int m = n / 2; TreeNode *root = new TreeNode(nums[m]); root->left = toBST(nums, m); root->right = toBST(nums+m+1, n-m-1); return root; }
相关推荐
leetcode-tag-array
LeetCode Remove Duplicates from Sorted Array解决方案
leetcode卡LeetCode---二分搜索 该存储库包括二进制搜索探索卡中所有问题的解决方案。
大佬的leetcode刷题笔记(c++版本)
leetcode 树节点leetcode 226 - 反转二叉树 方法一:递归 C# public TreeNode InvertTree ( TreeNode root ) { if ( root == null ) return root ; var temp = root . left ; root . left = root . right ; root . ...
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
leetcode 数据结构题目中的答案,已经调试,直接运行,求二叉树的最小深度
leetcode添加元素使和等于 LeetCode leetcode 指针类型题目 1. 链表 函数参数传入的链表都没有链表的头,从第一个有数据的节点开始 函数返回一个链表,这个链表也没有头 2. 内存分配 二维数组内存分配 二维数组分配...
LeetCode题解 - Java语言实现-181页.pdf
leetcode 答案Leetcode---数据库 我对 Leetcode 数据库问题的回答
彩色版本 正版 pdf 精讲数据结构 + 算法 链表 树 图表 贪心算法 指针 动态规划 查找算法
leetcode-tag-Tree
leetcode-训练 算法训练。 java $: javac hello.java java $: java hello c $: gcc hello.c 如果没有错误会生成a.out 可执行文件 c $: ./a.out leetcode cli leetcode version leetcode help leetcode help user ...
leetcode 答案leetcode--python Leetcode 的答案
leetcode卡 leetcode exercises 3-5 solutions everyday. fighting~ TODO array Best Time to Buy and Sell Stock II Valid Sudoku linked list Palindrome linked list Linked List Cycle trees Convert Sorted ...
leetcode伪代码merge-two-binary-tree 题目解读: 题目来源: 原文: Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the...
leetcode 接口 该项目可帮助您使用首选的 IDE 或带有命令行界面 (CLI) 的编辑器来执行 leetcode。 入门 先决条件 Windows 10、MacOS、Linux Chrome版 >=90.0.4430 安装 # Prepare your virtual environment conda ...