Bootstrap

Morris 二叉搜索树遍历模板

Morris Traversal是o(n)时间复杂度,o(1)空间复杂度的BST遍历方法。

下面是Morris Traversal模板:

public void morrisInorderTraverse() {
    Node cur = root;
    while (cur != null) {
        if (cur.left == null) {
            System.out.println(cur);
            cur = cur.right;
        } else {
            Node pre = cur.left;
            while(pre.right != null && pre.right != cur) {
                pre = pre.right;
            }
            if (pre.right == cur) {
                pre.right = null;
                System.out.println(cur);
                cur = cur.right;
            } else {
                pre.right = cur;
                cur = cur.left;
            }
        }
    }
}

public void morrisPreorderTraverse(){
    Node cur = root;
    while (cur != null ) {
        if (cur.left == null) {
            System.out.println(cur);
            cur = cur.right;
        } else {
            Node pre = cur.left;
            while (pre.right != null && pre.right != cur) {
                pre = pre.right;
            }
            if (pre.right == cur) {
                pre.right = null;
                cur = cur.right;
            } else {
                System.out.println(cur);
                pre.right = cur;
                cur = cur.left;
            }
        }
    }
}

 

;