主要的思想类似中序遍历,先构建左子树,再构建当前节点,并构建右子树
TreeNode *sortedListToBST(ListNode *head) {
int count = 0;
ListNode * cur = head;
while (cur)
{
count++;
cur = cur->next;
}
return sortedListToBST(head, count);
}
TreeNode *sortedListToBST(ListNode * (&head), int count) {
if (count <= 0) return NULL;
TreeNode* left = sortedListToBST(head, count / 2 );
TreeNode * root = new TreeNode(head->val);
head = head->next;
root->left = left;
root->right = sortedListToBST(head, count - (count / 2) - 1);
return root;
}
还有一个类似的题目:将二叉搜索树转换成双向链表
同样是类似中序遍历,先将左子树变成双向链表,再处理右子树
代码如下:
void BSTToList(TreeNode * t, ListNode * &l)
{
if (t->left) BSTToList(t->left, l);
ListNode * cur = new ListNode(t->val);
cur->left = l;
if (!l) l->right = cur;
l = cur;
if (t->right) BSTToList(t->right, l);
}