Morris遍历详解——实现二叉树的前序,中序遍历

Morris遍历
Morris遍历是指在线性时间内,利用空闲指针只占用常数空间来实现遍历,其主要思路如下

记当前节点指针为cur
1,若cur无左树,则cur=cur.right
2,若cur有左树,则找到其最右节点mostright,分为两种情况
(a)若mostright的右指针为空,则指向当前节点,cur左移
mostright.right=cur; cur=cur.left;
(b)若mostright的右指针指向当前cur,则说明第二次访问,又指回空,cur右移
mostright.right=null; cur=cur.right;

给定如下图所示的一棵二叉树,按照上述规则遍历,cur指针所指向的节点顺序如右。当一个节点有左子树时,其会被遍历两次,否则只遍历一次。Morris遍历是通过最右节点mostright是否指向cur来判断是第几次访问该节点。
Morris遍历详解——实现二叉树的前序,中序遍历_第1张图片

前序遍历
第一次访问该节点就是前序遍历

public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        TreeNode cur = root;
        TreeNode mostright = null;
        while (cur != null) {
            mostright = cur.left;
            if (mostright != null) {
                //注意是两个条件
                while (mostright.right != null && mostright.right != cur) {
                    mostright = mostright.right;
                }
                if (mostright.right == null) {
                    mostright.right = cur;
                    res.add(cur.val);
                    cur = cur.left;
                } else {
                    mostright.right = null;
                    cur = cur.right;
                }
            } else {                res.add(cur.val);
                cur = cur.right;
            }
        }
        return res;
    }

中序遍历
有左子树的节点第二次访问时才加入到列表中

 public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        TreeNode cur = root;
        TreeNode mostright = null;
        while (cur != null) {
            mostright = cur.left;
            if (mostright != null) {
                while (mostright.right != null && mostright.right != cur) {
                    mostright = mostright.right;
                }
                if (mostright.right == null) {
                    mostright.right = cur;
                    cur = cur.left;
                } else {
                    mostright.right = null;
                    res.add(cur.val);
                    cur = cur.right;
                }
            } else {
                res.add(cur.val);
                cur = cur.right;
            }
        }
        return res;
    }

你可能感兴趣的:(指针,二叉树,数据结构,算法)