其他分享
首页 > 其他分享> > Morris 二叉搜索树遍历模板

Morris 二叉搜索树遍历模板

作者:互联网

原文链接:http://www.learn4master.com/algorithms/morris-traversal-inorder-tree-traversal-without-recursion-and-without-stack

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

 

标签:pre,遍历,cur,System,二叉,Morris,right,null,left
来源: https://blog.csdn.net/zshouyi/article/details/100620657