欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链表转二叉树

程序员文章站 2022-05-19 21:08:46
...

题目

链表转二叉树

思路

找到链表的中点,然后递归

代码

def linkedlist_tree(link):
  if link is None:
    return None
  dummy = Node_L(None,0)
  dummy.next = link
  link = dummy
  fast = link
  slow = link
  pre = link
  while fast and fast.next is not None:
    pre = slow
    fast = fast.next.next
    slow = slow.next
  pre.next = None
  print(pre.value)

  root = Node(slow.value)
  root._left = linkedlist_tree(link.next)
  root._right = linkedlist_tree(slow.next)
  return root
相关标签: 二叉树