标签:leetcode
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
根据有序列表构造平衡的二叉查找树。关键在于二叉树保持平衡,但因为数组为有序的,所以直接取数组中间元素作为二叉树的根,再用左右区间构造左右子树,递归进行就好。
C++
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedArrayToBST(vector<int> &num) { if(num.size() == 0) return NULL; return build(num,0,num.size()); } TreeNode *build(vector<int>&num,int st, int ed) { if(st == ed) return NULL; int m = (st + ed)/2; TreeNode* root = new TreeNode(num[m]); root->left = build(num,st,m); root->right = build(num,m+1,ed); return root; } };
Python:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): if len(num) == 0: return None ans = self.build(num,0,len(num)) return ans def build(self,num,st,ed): if st == ed: return None m = (st + ed)/2 root = TreeNode(num[m]) root.left = self.build(num,st,m) root.right = self.build(num,m+1,ed) return root
【LeetCode】Convert Sorted Array to Binary Search Tree
标签:leetcode
原文地址:http://blog.csdn.net/jcjc918/article/details/43926805