二叉树的(前序、中序、后序、层次等遍历的)递归和非递归解法

版权声明:本文为博主原创文章,希望大家转载时注明出处。 https://blog.csdn.net/Angel_guoo/article/details/88946275

二叉树是一种非常重要的数据结构,其他很多数据结构都是基于二叉树基础演变而来的。

在我刷 剑指offer 中,碰到了  “ 二叉搜索树与双向链表 ” 这样的题目,对于里面的非递归解法很不理解,所以我就又重新复习了一遍二叉树的前序、中序、后序和层次遍历,以及求树的深度,广度等。

闲话少说,直接上代码,如果代码看不太懂,就自己画一颗二叉树,自己按照程序走一遍,多走几遍,然后看看相关文章的注释,就能弄懂了。

比如:

                   10

           7                 12

   6          8       11         14

前序遍历:  10 ,7,6,8,12,11, 14, 10

后序遍历:   6, 8, 7, 11, 14, 12, 10

中序遍历:   6,7, 8, 9, 10, 11, 12, 14

层次遍历:  10, 7, 12, 6 , 8 , 11 , 14

深度: 3

广度:  4

我这里只给出类似的代码,具体的相应修改,需要大家自己动手啦^_^

节点定义:

public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

1,前序遍历 (递归解法)

    public static void preOrder(TreeNode treeNode) {
        if (treeNode != null) {
            System.out.print(treeNode.val + " ");
            preOrder(treeNode.left);
            preOrder(treeNode.right);
        }
    }

2.1, 前序遍历(非递归解法①)

    /**
     * 先序非递归:
     * 这种实现类似于图的深度优先遍历(DFS)。
     * 维护一个栈,将根节点入栈,然后只要栈不为空,出栈并访问,
     * 接着依次将访问节点的右节点、左节点入栈。
     * 这种方式应该是对先序遍历的一种特殊实现(看上去简单明了),
     * 但是不具备很好的扩展性,在中序和后序方式中不适用
     *
     * @param root
     */
    public static void preOrderStack(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode treeNode = stack.pop();
            System.out.print(treeNode.val + " ");
            if (treeNode.right != null) {
                stack.push(treeNode.right);
            }
            if (treeNode.left != null) {
                stack.push(treeNode.left);
            }
        }
    }

 

2.2 先序遍历(非递归解法②)

/**
     * 先序非递归2:
     * 利用栈模拟递归过程实现循环先序遍历二叉树。
     * 这种方式具备扩展性,它模拟递归的过程,将左子树点不断的压入栈,直到null,
     * 然后处理栈顶节点的右子树。
     *
     * @param root
     */
    public static void preOrderStack2(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode treeNode = root;
        while (treeNode != null || !stack.isEmpty()) {
            //将左子树点不断的压入栈
            while (treeNode != null) {
                //先访问再入栈
                System.out.print(treeNode.val + " ");
                stack.push(treeNode);
                treeNode = treeNode.left;
            }
            //出栈并处理右子树
            if (!stack.isEmpty()) {
                treeNode = stack.pop();
                treeNode = treeNode.right;
            }

        }

    }

3,中序遍历(递归解法)

    public static void inOrder(TreeNode treeNode) {
        if (treeNode != null) {
            inOrder(treeNode.left);
            System.out.print(treeNode.val + " ");
            inOrder(treeNode.right);
        }
    }

4,中序遍历(非递归解法)

    /**
     * 中序非递归:
     * 利用栈模拟递归过程实现循环中序遍历二叉树。
     * 思想和上面的先序非递归2相同,
     * 只是访问的时间是在左子树都处理完直到null的时候出栈并访问。
     *
     * @param treeNode
     */
    public static void inOrderStack(TreeNode treeNode) {
        Stack<TreeNode> stack = new Stack<>();
        while (treeNode != null || !stack.isEmpty()) {
            while (treeNode != null) {
                stack.push(treeNode);
                treeNode = treeNode.left;
            }
            //左子树进栈完毕
            if (!stack.isEmpty()) {
                treeNode = stack.pop();
                System.out.print(treeNode.val + " ");
                treeNode = treeNode.right;
            }
        }
    }

5,后序遍历(递归解法)

    public static void postOrder(TreeNode treeNode) {
        if (treeNode != null) {
            postOrder(treeNode.left);
            postOrder(treeNode.right);
            System.out.print(treeNode.val + " ");
        }
    }

6,后序遍历(非递归解法①)

public static class TagNode {
        TreeNode treeNode;
        boolean isFirst;
    }

    /**
     * 后序非递归:
     * 后序遍历不同于先序和中序,它是要先处理完左右子树,
     * 然后再处理根(回溯)。
     * <p>
     * <p>
     * 对于任一结点P,将其入栈,然后沿其左子树一直往下搜索,直到搜索到没有左孩子的结点,
     * 此时该结点出现在栈顶,但是此时不能将其出栈并访问,因此其右孩子还为被访问。
     * 所以接下来按照相同的规则对其右子树进行相同的处理,当访问完其右孩子时,该结点又出现在栈顶,
     * 此时可以将其出栈并访问。这样就保证了正确的访问顺序。
     * 可以看出,在这个过程中,每个结点都两次出现在栈顶,只有在第二次出现在栈顶时,才能访问它。
     * 因此需要多设置一个变量标识该结点是否是第一次出现在栈顶,这里是在树结构里面加一个标记,然后合成一个新的TagNode。
     *
     * @param treeNode
     */
    public static void postOrderStack(TreeNode treeNode) {
        Stack<TagNode> stack = new Stack<>();
        TagNode tagNode;
        while (treeNode != null || !stack.isEmpty()) {
            //沿左子树一直往下搜索,直至出现没有左子树的结点
            while (treeNode != null) {
                tagNode = new TagNode();
                tagNode.treeNode = treeNode;
                tagNode.isFirst = true;
                stack.push(tagNode);
                treeNode = treeNode.left;
            }

            if (!stack.isEmpty()) {
                tagNode = stack.pop();
                //表示是第一次出现在栈顶
                if (tagNode.isFirst == true) {
                    tagNode.isFirst = false;
                    stack.push(tagNode);
                    treeNode = tagNode.treeNode.right;
                } else {
                    //第二次出现在栈顶
                    System.out.print(tagNode.treeNode.val + " ");
                    treeNode = null;
                }
            }
        }
    }

7,后序遍历(非递归解法②)

    /**
     * 后序非递归2:
     * 要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;
     * 或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。
     * 若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,
     * 左孩子和右孩子都在根结点前面被访问。
     *
     * @param treeNode
     */
    public static void postOrderStack2(TreeNode treeNode) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode currentTreeNode;
        TreeNode preTreeNode = null;
        stack.push(treeNode);

        while (!stack.isEmpty()) {
            currentTreeNode = stack.peek();
            //如果当前结点没有孩子结点或者孩子节点都已被访问过
            if ((currentTreeNode.left == null && currentTreeNode.right == null) ||
                    (preTreeNode != null && (preTreeNode == currentTreeNode.left || preTreeNode == currentTreeNode.right))) {
                System.out.print(currentTreeNode.val + " ");
                stack.pop();
                preTreeNode = currentTreeNode;
            } else {
                if (currentTreeNode.right != null) {
                    stack.push(currentTreeNode.right);
                }
                if (currentTreeNode.left != null) {
                    stack.push(currentTreeNode.left);
                }
            }
        }
    }
}

 8,层次遍历(递归解法)

public void levelOrder(BinaryNode<AnyType> Node) {
        if (Node == null) {
            return;
        }

        int depth = depth(Node);

        for (int i = 1; i <= depth; i++) {
            levelOrder(Node, i);
        }
    }

    private void levelOrder(BinaryNode<AnyType> Node, int level) {
        if (Node == null || level < 1) {
            return;
        }

        if (level == 1) {
            System.out.print(Node.element + "  ");
            return;
        }

        // 左子树
        levelOrder(Node.left, level - 1);

        // 右子树
        levelOrder(Node.right, level - 1);
    }

    public int depth(BinaryNode<AnyType> Node) {
        if (Node == null) {
            return 0;
        }

        int l = depth(Node.left);
        int r = depth(Node.right);
        if (l > r) {
            return l + 1;
        } else {
            return r + 1;
        }
    }

9,层序遍历(非递归解法)

public void levelOrder(BinaryTreeNode root){
	 Queue<BinaryTreeNode> queue=new LinkedList<BinaryTreeNode>();
	 queue.offer(root);
	 while(!queue.isEmpty()){
		 temp=queue.poll();
		 System.out.print(temp.getData()+"\t");
		 if(null!=temp.getLeft()) 
			 queue.offer(temp.getLeft());
		 if(null!=temp.getRight()){
			 queue.offer(temp.getRight());
		}
	}
}

10,求二叉树深度

// 获取最大深度
    public static int getMaxDepth(TreeNode root) {
        if (root == null)
            return 0;
        else {
            int left = getMaxDepth(root.left);
            int right = getMaxDepth(root.right);
            return 1 + Math.max(left, right);
        }
    }

11, 求二叉树广度

// 获取最大宽度
    public static int getMaxWidth(TreeNode root) {
        if (root == null)
            return 0;

        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        int maxWitdth = 1; // 最大宽度
        queue.add(root); // 入队

        while (true) {
            int len = queue.size(); // 当前层的节点个数
            if (len == 0)
                break;
            while (len > 0) {// 如果当前层,还有节点
                TreeNode t = queue.poll();
                len--;
                if (t.left != null)
                    queue.add(t.left); // 下一层节点入队
                if (t.right != null)
                    queue.add(t.right);// 下一层节点入队
            }
            maxWitdth = Math.max(maxWitdth, queue.size());
        }
        return maxWitdth;
    }

参考文章:

1, http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html

2, https://www.cnblogs.com/wylwyl/p/10477528.html

3, https://blog.csdn.net/lr131425/article/details/60755706

4, https://blog.csdn.net/apandi_/article/details/52916523

5, https://www.cnblogs.com/qiuyong/p/6675492.html
6,
https://www.cnblogs.com/morethink/p/7265817.html

7,https://www.cnblogs.com/liuyang0/p/6271324.html

8, https://blog.csdn.net/zhangxiangdavaid/article/details/37115355

9,https://www.cnblogs.com/xudong-bupt/p/4036190.html

10, https://blog.csdn.net/lr131425/article/details/60755706

猜你喜欢

转载自blog.csdn.net/Angel_guoo/article/details/88946275