[CareerCup][Google Interview] Merge Two BST

You have two BST, you have to merge them into a single BST, inplace and linear time.

http://www.careercup.com/question?id=8255895

 

 

其中,一位仁兄给出了一个非常漂亮的解答:

we could do it in O(m+n) (m, n sizes of both bsts)
1) Covert Tree1 in to circular doubly linked list. O(m)
Search for "tree list recursion problem" for more details.
2) Convert Tree2 in to circular doubly linked list O(n).
3) Merge Tree1, Tree2 O(m+n)
4) Convert the merged circular doubly linked list to Tree. O(m+n) (Middle node can be chosen as root to make tree balanced).

其中doubly link list,tree node的left和right正好作为链表的前后链接。

当然,要写好每一步其实也不容易的。

1)如何把tree转换为doubly link list

2) 如何merge两个list

3) 如何把doubly link list转换为tree

每一个都值得一写,等有时间了把代码写一下。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值