Prove safety offer: binary search trees and doubly-linked list (java)

Title: Enter a binary search tree, converts the binary search tree into a sort of two-way linked list. Not required to create a new node, only the tree nodes point to adjust the pointer.

For example the following figures binary search tree, sorted doubly linked list output after conversion to:

    Since after the list is sorted in claim conversion, we can each node in a preorder traversal of the tree, this is because the order of traversal algorithm characterized by each node in ascending order according to the binary tree traversal. When the root node traversed, we put the tree as three parts: the value of the node 10, the root node 6 of the left subtree, the root node 14 of the right subtree. According to the definition of the ordered list, the junction point 10 and the value of its left subtree of a node linked maximum, minimum and at the same time it is also the right subtree nodes linked together. In the order of traversal sequence, when we traverse conversion to the root node, its left subtree has been converted into a sorted linked list, and the last node in the list is the largest value of the current node. Then we went to traverse the conversion right subtree and right subtree and the root node in the smallest linked. Left and right sub-tree of the same conversion method, it is natural to think you can do it using recursive.

    public BinaryTreeNode convert(BinaryTreeNode root){  
        BinaryTreeNode node = null;  
        convert(root,node);  
        while(node != null && node.leftNode != null){  
            node = node.leftNode;  
        }  
        return node;  
    }  
    public void convert(BinaryTreeNode root,BinaryTreeNode lastNode){  
        if(root == null)  
            return;  
        BinaryTreeNode current = root;  
        if(current.leftNode != null)  
            convert(current.leftNode,lastNode);  
        current.leftNode = lastNode;  
        if(lastNode != null)  
            lastNode.rightNode = current;  
        if(current.rightNode != null)  
            convert(current.rightNode,lastNode);  
    } 


Published 118 original articles · won praise 35 · views 120 000 +

Guess you like

Origin blog.csdn.net/abc7845129630/article/details/52729677