线索化中序、先序、后序遍历二叉树的方式(待补充完整)

来源:互联网 发布:单片机dl是什么意思啊 编辑:程序博客网 时间:2024/04/29 14:37

线索化遍历优点在于不需要递归和栈,空间复杂度降到O(1),且时间复杂度仍未O(n)。

期间会暂时修改树的数据结构,遍历结束后恢复。


线索化中序遍历二叉树

public void morrisTraversal(TreeNode root){        TreeNode temp = null;        while(root!=null){            if(root.left!=null){                // connect threading for root                temp = root.left;                while(temp.right!=null && temp.right != root)                    temp = temp.right;                // the threading already exists                if(temp.right!=null){                    temp.right = null;                    System.out.println(root.val);                    root = root.right;                }else{                    // construct the threading                    temp.right = root;                    root = root.left;                }            }else{                System.out.println(root.val);                root = root.right;            }        }    }


0 0
原创粉丝点击