leetcode - binary search tree becomes doubly linked list

Title Description

Enter a binary search tree, the binary search tree converted into a doubly linked list sorted. Requirements can not create any new node, point to only adjust the tree node pointer.

Thinking

I swear, after to use recursion, killing do not stack. Recursion too easy!

Thinking: store all the nodes in order traversal sequence with a list. Then they change pointers

class Solution:
    # 中序遍历 - 递归方法
    def midS(self,root,result):
        if root.left:                    # 遍历左子树
            self.midS(root.left,result)
        result.append(root)              # root
        if root.right:                   # 遍历右子树
            self.midS(root.right,result)
        return result
    
    def Convert(self, root):
        if not root:
            return None
        nodes = self.midS(root,[])
        for i in range(0,len(nodes)-1):
            nodes[i].right = nodes[i+1]
            nodes[i+1].left = nodes[i]
        return nodes[0]
        

 

Published 82 original articles · won praise 2 · Views 4362

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104758510
Recommended