码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Convert Sorted Array to Binary Search Tree

时间:2015-04-22 20:43:17      阅读:122      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!