BST(搜索二叉树)与双向链表相互转换

1.BST->双向链表

a.中序遍历(有序)

b.插入节点

树结构

package BSTLinkList;

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}

public class BSTToLinkList {
    private TreeNode pre;
    private TreeNode head;
    public TreeNode Convert(TreeNode root) {
        visit(root);
        return head;
    }
    private void visit(TreeNode root){
        visit(root.left);
        create(root);
        visit(root.right);
    }
    private void create(TreeNode treeNode){
        treeNode.left = pre;
        if (pre==null)
            head = treeNode;
        else
            pre.right = treeNode;
        pre = treeNode;
    }
}

2.双向链表->BST

public class LinkListToBST {
    TreeNode root;
    public TreeNode Convert(TreeNode head) {
        int cnt = 0;
        TreeNode cur = head;
        while(cur!=null){
            cur = cur.right;
        }
        return create(head,0,cnt-1);
    }
    private TreeNode create(TreeNode head, int left, int right){
        if (left>right)
            return null;
        int mid = left + (right - left)/2;
        TreeNode leftChild = create(head,left,mid-1);
        TreeNode parent = new TreeNode(head.val);
        parent.left = leftChild;
        head = head.right;
        parent.right = create(head,mid+1,right);
        return parent;
    }
}

你可能感兴趣的:(java)