二叉树的三种非递归遍历和morris遍历

来源:互联网 发布:淘宝宝贝描述图片宽度 编辑:程序博客网 时间:2024/05/22 07:31

1、先序遍历

public static void printPreOrder(TreeNode node) {        Queue<TreeNode> queue = new LinkedList<TreeNode>();        if (node == null)            return;        queue.offer(node);        while (!queue.isEmpty()) {            TreeNode temp = queue.poll();            System.out.println(temp.val);            if (temp.left != null)                queue.offer(temp.left);            if (temp.right != null)                queue.offer(temp.right);        }    }

2、中序遍历

public static void printInOrder(TreeNode node) {        Stack<TreeNode> stack = new Stack<TreeNode>();        if (node == null)            return;        TreeNode temp = node;        while (temp != null || !stack.isEmpty()) {            while (temp != null) {                stack.add(temp);                temp = temp.left;            }            temp = stack.pop();            System.out.println(temp.val);            temp = temp.right;        }    }

3、后序遍历

public static void printPostOrder(TreeNode node) {        Stack<TreeNode> stack = new Stack<TreeNode>();        if (node == null)return;        TreeNode temp = node;        TreeNode pre = null;        while (temp != null || !stack.isEmpty()) {            while (temp != null) {                stack.add(temp);                temp = temp.left;            }            temp = stack.pop();            while (temp!=null&&(temp.right == null || pre == temp.right)) {                pre = temp;                System.out.println(temp.val);                if(stack.isEmpty())return;                temp=stack.pop();            }            stack.add(temp);            temp = temp.right;        }    }

4、morris遍历是一种很神奇的遍历,上述的三种方法和递归遍历方法都需要O(n)的时间,O(n)的空间,而morris遍历则只需要O(n)的时间,O(1)的空间。下面以morris中序遍历来说明。
算法伪代码如下:
MorrisInOrder():
while 没有结束
如果当前节点没有左孩子
访问该节点
转向该节点的右孩子
否则
找到左孩子的最右节点。
如果最右节点的右孩子不为空则说明最右节点已和当前节点连接,访问当前节点,并把最右节点的只有孩子置为空,转向当前节点的右孩子。
如果最右节点的右孩子为空,则使最右节点的右孩子指向当前节点,转向当前节点的左孩子。

public static void morrisInOrder(TreeNode root){        TreeNode cur=root;        while(cur!=null){            if(cur.left==null){                System.out.println(cur.val);                cur=cur.right;            }else{                TreeNode temp=cur.left;                while(temp.right!=null&&temp.right!=cur){                    temp=temp.right;                }                if(temp.right==cur){                    System.out.println(cur.val);                    temp.right=null;                    cur=cur.right;                }else{                    temp.right=cur;                    cur=cur.left;                }            }        }    }
0 0
原创粉丝点击