"Sword refers to Offer"-26, binary search tree and doubly linked list

1. Knowledge points of this question

tree

2. Title description

Enter a binary search tree and convert the binary search tree into a sorted doubly linked list. It is required that no new nodes can be created, and only the point of the node pointer in the tree can be adjusted.

3. Problem solving ideas

In order to traverse the binary search tree, then use an ArrayList class to save the results of the traversal, and finally modify the pointer.

4. Code

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

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

    }
}
import java.util.ArrayList;

public class Solution {
    
    
    ArrayList<TreeNode> list = new ArrayList<>();

    public TreeNode Convert(TreeNode pRootOfTree) {
    
    
        if (pRootOfTree == null) {
    
    
            return null;
        }
        InOrderTraverse(pRootOfTree);
        // 修改指针
        for (int i = 0; i < list.size() - 1; i++) {
    
    
            list.get(i).right = list.get(i + 1);
            list.get(i + 1).left = list.get(i);
        }
        return list.get(0);
    }

    // 中序遍历二叉搜索树,然后用一个 ArrayList 类保存遍历的结果
    public void InOrderTraverse(TreeNode pRootOfTree) {
    
    
        if (pRootOfTree.left != null) {
    
    
            InOrderTraverse(pRootOfTree.left);
        }
        list.add(pRootOfTree);
        if (pRootOfTree.right != null) {
    
    
            InOrderTraverse(pRootOfTree.right);
        }
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112986690
Recommended