Sword se refiere a la oferta 36. Árbol de búsqueda binaria y lista doblemente enlazada

Sword se refiere a la oferta 36. Árbol de búsqueda binaria y lista doblemente enlazada

Descripción del Título

Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

Ideas para resolver problemas

El recorrido en orden del árbol de búsqueda binaria es la lista enlazada secuencial.

Esta pregunta también utiliza el método de recorrido en orden del registro predecesor .

class Solution {
    
    
    Node head, pre;
    public Node treeToDoublyList(Node root) {
    
    
        if (root == null) return null;
        //将树转化为双向链表,pre最后停留在尾节点上
        inorderTraversal(root);
        //将 双向链表 转化为 双向循环链表
        head.left = pre;
        pre.right = head;
        return head;
    }
    
    //中序遍历,将以root为根节点的树转化为双向链表
    public void inorderTraversal(Node root) {
    
    
        if (root == null) return;
        inorderTraversal(root.left);

        if (pre != null) {
    
    
            pre.right = root;
        } else {
    
    
            head = root;   //双向链表的头结点
        }
        root.left = pre;
        pre = root;   //记录前驱

        inorderTraversal(root.right);
    }
}

Supongo que te gusta

Origin blog.csdn.net/cys975900334/article/details/115199298
Recomendado
Clasificación