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) {
            return null;
        if(pRootOfTree.left==null && pRootOfTree.right==null){
            return pRootOfTree;
        TreeNode left=Convert(pRootOfTree.left);
        TreeNode right=Convert(pRootOfTree.right);
        return left!=null ? left : pRootOfTree;

Guess you like