Morris 遍历

Morris遍历的规则

​ 假设来到当前节点 cur != null

  1. 如果 cur 无左孩子,cur = cur.right
  2. 如果 cur 有左孩子,找到左子树的最右节点,记为 cur1
    • 如果 cur1.right == null,让其指针指向 cur,(cur = cur.left
    • 如果 cur1.right == cur,让其指向空,cur = cur.right

Morris 遍历_第1张图片

  • 橙色:指针移动操作,A = A.next。
  • 绿色:更改指针指向, A.left = B。
  • 黄色:指针指向位置。

代码

public class MorrisT {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) { val = x; }
    }
    public static void morrisTran(TreeNode root){
        if (root == null){
            return;
        }
        TreeNode cur = root;
        TreeNode cur1 = null;
        while(cur != null){
            cur1 = cur.left;
            if (cur1 != null){
                while(cur1.right != null && cur1.right != cur){
                    cur1 = cur1.right;
                }
                if (cur1.right == null){
                    cur1.right = cur;
                    cur = cur.left;
                    continue;
                }
                cur1.right = null;
            }
            cur = cur.right;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        morrisTran(root);
    }
}

你可能感兴趣的:(二叉树)