LINTCODE---排序列表转换为二分查找树

LINTCODE—排序列表转换为二分查找树

思路:主要就是用快慢指针找出中间点,作为一个伪“顶点”,然后递归调用自身,返回左右节点;

class Solution {
public:
    /*
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    TreeNode * sortedListToBST(ListNode * head) {
        // write your code here
        if(head == NULL )
            return NULL;
        if(head -> next == NULL)
            return new TreeNode(head -> val);

        //快慢指针找到中间点
        ListNode *slow = head ,*fast = head ,*temp = head;
        while(fast != NULL && fast->next != NULL)
        {
            temp = slow;
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        temp -> next = NULL;

        // 递归调用自身
        TreeNode *resTree = new TreeNode(slow -> val);
        resTree -> left = sortedListToBST(head);
        resTree -> right = sortedListToBST(slow -> next);

        return resTree;

    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值