Python二叉搜索树与双向链表转换算法示例

时间:2022-10-26 14:08:07

本文实例讲述了Python二叉搜索树与双向链表转换算法。分享给大家供大家参考,具体如下:

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

普通的二叉树也可以转换成双向链表,只不过不是排序的

思路:

1. 与中序遍历相同

2. 采用递归,先链接左指针,再链接右指针

代码1,更改doubleLinkedList,最后返回list的第一个元素:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class TreeNode:
  def __init__(self, x):
    self.val = x
    self.left = None
    self.right = None
class Solution:
  def lastElem(self, list):
    if len(list) == 0:
      return None
    else: return list[len(list) - 1]
  def ConvertCore(self, pRoot, doubleLinkedList):
    if pRoot:
      if pRoot.left:
        self.ConvertCore(pRoot.left, doubleLinkedList)
      pRoot.left = self.lastElem(doubleLinkedList)
      if self.lastElem(doubleLinkedList):
        self.lastElem(doubleLinkedList).right = pRoot
      doubleLinkedList.append(pRoot)
      if pRoot.right:
        self.ConvertCore(pRoot.right, doubleLinkedList)
  def Convert(self, pRootOfTree):
    if pRootOfTree == None:
      return None
    doubleLinkedList = []
    self.ConvertCore(pRootOfTree, doubleLinkedList)
    return doubleLinkedList[0]

代码2,lastListNode指向双向链表中的最后一个节点,因此每次操作最后一个节点。这里要更改值,因此采用list的形式。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class TreeNode:
  def __init__(self, x):
    self.val = x
    self.left = None
    self.right = None
class Solution:
  def ConvertCore(self, pRoot, lastListNode):
    if pRoot:
      if pRoot.left:
        self.ConvertCore(pRoot.left, lastListNode)
      pRoot.left = lastListNode[0]
      if lastListNode[0]:
        lastListNode[0].right = pRoot
      lastListNode[0] = pRoot
      if pRoot.right:
        self.ConvertCore(pRoot.right, lastListNode)
  def Convert(self, pRootOfTree):
    # write code here
    if pRootOfTree == None:
      return None
    lastListNode = [None]
    self.ConvertCore(pRootOfTree, lastListNode)
    while lastListNode[0].left:
      lastListNode[0] = lastListNode[0].left
    return lastListNode[0]

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/weixin_36372879/article/details/84258821