网络编程
位置:首页>> 网络编程>> Python编程>> Python二叉搜索树与双向链表转换算法示例

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

作者:hustfc  发布时间:2023-07-17 22:49:42 

标签:Python,二叉搜索树,双向链表

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

题目描述

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

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

思路:

1. 与中序遍历相同

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

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


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的形式。


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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com