109. Convert Sorted List to Binary Search Tree (List; Divide-and-Conquer, dfs)
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/** * 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) { if(!head) return NULL; int size = 1; ListNode * listNode = head->next; while(listNode) { size++; listNode = listNode->next; } TreeNode* root = new TreeNode(0); binarySearch(head,size,root); return root; } void binarySearch(ListNode *head,int size, TreeNode* treeNode) //二分法,对于Array,需要一头一尾两个指针;对于List需要头指针及size { if(size == 1) { treeNode->val = head->val; return; } ListNode * listNode = head; int mid = size>>1; int i; for(i = 1 ; i<mid;i++) { listNode = listNode ->next; } treeNode->val = listNode->next->val; treeNode->left = new TreeNode(0); //先申请好空间,再传递。否则在被调用函数中指针本身值的变化并不会影响调用者 binarySearch(head,mid,treeNode->left); if(size>2) { treeNode->right = new TreeNode(0); binarySearch(listNode->next->next,size-mid-1,treeNode->right); } } };
也可以通过引用传递,这样就不需要先初始化。
/** * 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) { if(!head) return NULL; int size = 1; ListNode * listNode = head->next; while(listNode) { size++; listNode = listNode->next; } TreeNode* root = new TreeNode(0); binarySearch(head,size,root); return root; } void binarySearch(ListNode *head,int size, TreeNode* &treeNode) //按引用传递参数 { if(size == 1) { treeNode=new TreeNode(head->val); return; } ListNode * listNode = head; int mid = size>>1; for(int i = 1 ; i<mid;i++) { listNode = listNode ->next; } treeNode = new TreeNode (listNode->next->val); //在被调用处申请空间 binarySearch(head,mid,treeNode->left); //引用的是0x0000的地址 if(size>2) { binarySearch(listNode->next->next,size-mid-1,treeNode->right); } } };
注意,NULL是一个宏定义
#define NULL 0
即NULL = (void*) 0