Old Wei wins the offer to take you to learn --- Brush title series (26 binary search trees and doubly-linked list)

26. The binary search trees and doubly-linked list

problem:

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.

solve:

thought:

This question is a test of a binary tree in order traversal features. We need to know in order traversal ** binary tree is going to get their sort order. ** we According to this feature, you can in order binary tree traversal, and then use a doubly linked list, you can sort them according to their way linked list.
Here Insert Picture Description

python code:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pHead):
        # write code here
        
        self.LastNode=None
        self.inorder(pHead)
        while(self.LastNode and self.LastNode.left):   ###从后往前寻找头节点。
            self.LastNode=self.LastNode.left
        return self.LastNode
    def inorder(self,root):
        if root:
            current=root
            if root.left:
                self.inorder(root.left)
            
            current.left=self.LastNode   ### 这里建立双向链表
            if(self.LastNode):
                self.LastNode.right=current
                
            self.LastNode=current   ###每次使LastNode指向新访问的节点(B,A,C)
                
            if root.right:
                self.inorder(root.right)

Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104954424