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

LeetCode: Convert Sorted List to Binary Search Tree [109]

时间:2014-06-07 16:20:05      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.



【题意】

将一个有序链表转换成平衡二叉树


【思路】


思路跟Convert Sorted Array to Binary Search Tree完全一样


【代码】

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    ListNode *getMidNode(ListNode *head){
        if(head==NULL || head->next==NULL)return head;
        ListNode* prev=NULL;        //指向pstep1的前一个节点
        ListNode* pstep1=head;      //每次向前移动一步
        ListNode* pstep2=head->next;    //每次向前移动两步
        //对于偶数链表,结束条件是pstep2->next==NULL
        //对于计数链表,结束条件是pstep2==NULL
        
        while(pstep2!=NULL && pstep2->next!=NULL){
            prev=pstep1;
            pstep1=pstep1->next;
            pstep2=pstep2->next->next;
        }
        
        //找到链表中间节点的同时,把链表分裂为前后两个独立的链表
        if(prev)prev->next=NULL;
        
        return pstep1;
    }

    TreeNode *sortedListToBST(ListNode *head) {
       if(head==NULL)return NULL;
       
       ListNode*mid=getMidNode(head);
       //创建根节点
       TreeNode*root=(TreeNode*)malloc(sizeof(TreeNode));
       root->val=mid->val;
       //创建左子树
       TreeNode*left=NULL;
       if(mid!=head)
            left=sortedListToBST(head);
       //创建右子树
       TreeNode*right=sortedListToBST(mid->next);
       //构造二叉树
       root->left=left;
       root->right=right;
       
       return root;
       
    }
};


LeetCode: Convert Sorted List to Binary Search Tree [109],布布扣,bubuko.com

LeetCode: Convert Sorted List to Binary Search Tree [109]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/28384107

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