Title Description
Enter a binary search tree and convert the two-fork search tree into a sorted doubly linked list. Requires that no new nodes can be created, only the point pointer of the node in the tree can be adjusted.
Title Address
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=2&rp=2 &ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
Ideas
Binary search tree as shown, we convert it to sort doubly linked list
According to the characteristics of the binary search tree: The value of the left node < The value of the root node < The value of the right node, it is not difficult to find that the ordering of the data traversed by the middle sequence of the two-fork tree is the order of the ordering. Therefore, the traversal method of the two-fork search tree is determined.
Next, we can divide the tree into three parts, a node with a value of 10, a left subtree with a root node of 6, and a right subtree with 14 root nodes. Based on the definition of a sorted doubly linked list, a node with a value of 10 is linked to the largest node of its left subtree, and it is linked to the smallest node in the right subtree.
According to the order of the middle order traversal, when we traverse to the root node, its left subtree has been converted into a sort of good doubly linked list, and the last node in the list is the node with the largest current value. We link a node with a value of 8 and a root node, and 10 becomes the last node, and then we go through the right subtree and link the root node to the smallest node in the right sub-tree. Finally, the setting starts at the leftmost node.
Python
#-*-coding:utf-8-*-classTreeNode:def __init__(self,x): Self.val=x self.left=None self.right=Nonenode1= TreeNode (8) Node2= TreeNode (6) Node3= TreeNode (14) Node4= TreeNode (4) Node5= TreeNode (8) Node6= TreeNode (12) Node7= TreeNode (16) Node1.left=Node2node1.right=Node3node2.left=Node4node2.right=Node5node3.left=Node6node3.right=Node7classSolution:defConvert (Self, prootoftree):#Write code here if notProotoftree:returnProotoftreeif notProotoftree.left and notProotoftree.right:returnProotoftree Self. Convert (prootoftree.left) left=Prootoftree.leftifLeft : whileLeft.right:left=left.right Prootoftree.left=Left Left.right=Prootoftree Self. Convert (prootoftree.right) right=Prootoftree.rightifRight : whileRight.left:right=Right.left prootoftree.right=Right Right.left=Prootoftree#start with the leftmost node . whilePRootOfTree.left:pRootOfTree=Prootoftree.leftreturnProotoftreeif __name__=='__main__': Result= Solution (). Convert (Node1)
The sword refers to offer 26. Binary search tree and doubly linked list (binary search tree)