标签:one lin convert treenode ref recursion tag tno init
1.Leetcode tag-LinkList 109.convert sorted list to binary search tree
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return RecursionListToBST(head,NULL);
}
TreeNode* RecursionListToBST(ListNode* head,ListNode *tail){
// linklist is empty
if(head==tail)
return NULL;
// only one node in the tree
if(head->next==tail){
TreeNode *root=new TreeNode(head->val);
return root;
}
// search the middle node
// excllent code segment need memorize.
ListNode *mid=head;
ListNode *temp=head;
while(temp!=tail && temp->next!=tail){
mid=mid->next;
temp=temp->next->next;
}
TreeNode *root=new TreeNode(mid->val);
root->left=RecursionListToBST(head,mid);
root->right=RecursionListToBST(mid->next,tail);
return root;
}
};
// 寻找链表重点这个真的是棒
ListNode *mid=head;
ListNode *temp=head;
while(temp!=tail && temp->next!=tail){
mid=mid->next;
temp=temp->next->next;
}
标签:one lin convert treenode ref recursion tag tno init
原文地址:https://www.cnblogs.com/GeekDanny/p/10092336.html