1. 程式人生 > >BST(搜尋二叉樹)與雙向連結串列相互轉換

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; } }