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

yipeiwu_com5年前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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

python关于矩阵重复赋值覆盖问题的解决方法

本文实例讲述了python关于矩阵重复赋值覆盖问题的解决方法。分享给大家供大家参考,具体如下: import itertools import numpy as np comb =...

Python实现简单的文本相似度分析操作详解

本文实例讲述了Python实现简单的文本相似度分析操作。分享给大家供大家参考,具体如下: 学习目标: 1.利用gensim包分析文档相似度 2.使用jieba进行中文分词 3.了解TF-...

根据tensor的名字获取变量的值方式

需求: 有时候使用slim这种封装好的工具,或者是在做滑动平均时,系统会帮你自动建立一些变量,但是这些变量只有名字,而没有显式的变量名,所以这个时候我们需要使用那个名字来获取其对应的值。...

Python tkinter实现图片标注功能(完整代码)

.tkinter tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinte...

python 实现将Numpy数组保存为图像

第一种方案 可以使用scipy.misc,代码如下: import scipy.misc misc.imsave('out.jpg', image_array) 上面的scipy版...