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

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

作者: goodAndBad | 来源:发表于2017-11-16 12:56 被阅读0次

    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

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/avjlvxtx.html