## The sword refers to the offer binary search tree and doubly linked list

### The basic idea

Use recursion to perform in-order traversal of the binary search tree, first convert the left subtree into a doubly linked list, connect the last node of the left subtree linked list to the root node in both directions, and then recursively convert the right subtree to convert the right subtree into a doubly linked list. The first node of the converted subtree is connected to the root node, and finally, according to whether the left subtree is empty, it can decide to return to the first node of the left subtree or return to the root node. During the traversal process, a variable last is used to record the last node of the left subtree, so as to avoid the need to relocate the last node of the left subtree linked list every time the left subtree and the root node are connected.

### AC Code (Java)

/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
private static TreeNode last=null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree==null){
return null;
}
if(pRootOfTree.left==null && pRootOfTree.right==null){
last=pRootOfTree;
return pRootOfTree;
}
//将左子树转换成双向链表
TreeNode left=Convert(pRootOfTree.left);
if(left!=null){
last.right=pRootOfTree;
pRootOfTree.left=last;
}
last=pRootOfTree;
TreeNode right=Convert(pRootOfTree.right);
if(right!=null){
right.left=pRootOfTree;
pRootOfTree.right=right;
}
return left!=null ? left : pRootOfTree;
}
}

### Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325525521&siteId=291194637
Recommended
Ranking
Daily