程序员人生 网站导航

Convert Sorted List to Binary Search Tree [leetcode] O(n)的算法

栏目:codeigniter时间:2014-10-09 07:40:56

主要的思想类似中序遍历,先构建左子树,再构建当前节点,并构建右子树

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); }


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐