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

Convert Sorted List to Binary Search Tree [leetcode] O(n)的算法

时间:2014-09-26 11:41:08      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:leetcode

主要的思想类似中序遍历,先构建左子树,再构建当前节点,并构建右子树

TreeNode *sortedListToBST(ListNode *head) {
        int count = 0;
        ListNode * cur = head;
        while (cur)
        {
            count++;
            cur = cur->next;
        }
        return sortedListToBST(head, count);
    }
    
    TreeNode *sortedListToBST(ListNode * (&head), int count) {
        if (count <= 0) return NULL;
        TreeNode* left = sortedListToBST(head, count / 2 );
        TreeNode * root = new TreeNode(head->val);
        head = head->next;
        root->left = left;
        root->right = sortedListToBST(head, count - (count / 2) - 1);
        return root;
    }

还有一个类似的题目:将二叉搜索树转换成双向链表

同样是类似中序遍历,先将左子树变成双向链表,再处理右子树

代码如下:

void BSTToList(TreeNode * t, ListNode * &l)
{
	if (t->left) BSTToList(t->left, l);
	ListNode * cur = new ListNode(t->val);
	cur->left = l;
	if (!l) l->right = cur;
	l = cur;
	if (t->right) BSTToList(t->right, l);
}


Convert Sorted List to Binary Search Tree [leetcode] O(n)的算法

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39577553

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