[Offer] [36] [binary search trees and doubly-linked list]

Title Description

  Enter a binary search tree , the binary search tree is converted into a doubly linked list sorted . Requirements can not create any new node , point to nodes in the tree can only adjust the pointer. For example, enter the left side in FIG binary search tree, sorted doubly linked list is output after conversion.
  


 

Cattle brush off questions address network

Ideas analysis

  Use in order traversal of thought, when we traverse to the root node, its left subtree has been converted into a sort of a list, and in the last node in the list is the greatest value of a node, the node and the root node connected at this time is the last node in the list of the root, then traverse right subtree, the root node and the connecting node with the smallest tree in the right child.

Test Case

  1. Function Test: binary input is complete binary tree; all nodes are not binary left / right subtree; only one node of a binary tree.
  2. Special input test: binary tree root node pointer pointing nullptr pointer.

Java code

public class Offer36 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static TreeNode Convert(TreeNode pRootOfTree) {
        return Solution1(pRootOfTree);
    }

    private static TreeNode Solution1(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return pRootOfTree;
        }
        TreeNode lastNodeInList = null;
        lastNodeInList = covertCore(pRootOfTree, lastNodeInList);
        TreeNode firstNodeInList = lastNodeInList;
        while (firstNodeInList != null && firstNodeInList.left != null) {
            firstNodeInList = firstNodeInList.left;
        }
        return firstNodeInList;
    }

    private static TreeNode covertCore(TreeNode pRootOfTree, TreeNode lastNodeInList) {
        if (pRootOfTree.left != null) {
            lastNodeInList = covertCore(pRootOfTree.left, lastNodeInList);
        }
        pRootOfTree.left = lastNodeInList;
        if (lastNodeInList != null) {
            lastNodeInList.right = pRootOfTree;
        }

        lastNodeInList = pRootOfTree;
        if (pRootOfTree.right != null) {
            lastNodeInList = covertCore(pRootOfTree.right, lastNodeInList);
        }

        return lastNodeInList;
    }

    private static void test1() {

    }

    private static void test2() {

    }

    private static void test3() {

    }
}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer36-er-cha-sou-suo-shu-yu-shuang-xiang-lian-bi.html
Recommended