将一个二叉查找树按照中序遍历转换成双向链表。

2017.11.16


image.png
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
Definition of Doubly-ListNode
class DoublyListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = self.prev = next
"""

class Solution:
    """
    @param root, the root of tree
    @return: a doubly list node
    """
    a = []
    def bstToDoublyList(self, root):
        # Write your code here
        if root == None:
            return None
        self.left(root)
        b = self.a[0]
        if len(self.a) == 1:
            return b
        for i in range(len(self.a)):
            if i == 0:
                self.a[i].next = self.a[i+1]
                continue
            if i == len(self.a) - 1:
                self.a[i].prev = self.a[i-1]
                continue
            self.a[i].next = self.a[i+1]
            self.a[i].prev = self.a[i-1]
            
        return b
                
    def left(self,root):
        if root == None:
            return
        self.left(root.left)
        self.a.append(DoublyListNode(root.val))
        self.right(root.right)
    def right(self,root):
        if root == None:
            return
        self.left(root.left)
        self.a.append(DoublyListNode(root.val))
        self.right(root.right)

一个能打的都没有。2017.11.16

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容