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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ListLength(ListNode *head) { int len=0; while(head) { head=head->next; len++; } return len; } TreeNode *createBST(ListNode *head,int left,int right) { if(left>right) return NULL; int mid=(left+right)>>1; ListNode *cur=head; for(int i=left;i<mid;i++) cur=cur->next; TreeNode *leftTree=createBST(head,left,mid-1); TreeNode *rightTree=createBST(cur->next,mid+1,right); TreeNode *root=new TreeNode(cur->val); root->left=leftTree; root->right=rightTree; return root; } TreeNode *sortedListToBST(ListNode *head) { if(head==NULL) return NULL; int len; len=ListLength(head); return createBST(head,0,len-1); } };