Z字型遍历二叉树Java实现

  • Z字型遍历二叉树java实现
    • 一.Java实现

Z字型遍历二叉树Java实现

大厂面试经常会问的一道算法题,这里记录一下

题目:
按照z字形层次遍历二叉树(以根节点所在层为第1层,则第二层的变量从右边节点开始直到最左边节点,第三层遍历则是从最左边开始到最右边)

思路:
添加一个 flag 标识当前层遍历是正向还是逆向,并通过 Deque 来充当栈,分别记录当前层和下一层二叉树的 Node,遍历完一层保存到 result 结果中,反转 flag 标识,并将下一层 Deque 赋值给当前层,下一层清空。

动动发财小手,关注 + 点赞 + 收藏不迷路。

一.Java实现

package tree;


import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: tinker
 * @Date: 2022/01/15 14:50
 */
public class ZigzagLevelOrder {

    public static void main(String[] args) {
        /*
        build tree
                1
               / \
              2   3
                 / \
                4   5
         */
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);

        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode3.left = treeNode4;
        treeNode3.right = treeNode5;

        /**
         * it should print:
         * 1
         * 3 2
         * 4 5
         */
        zigzagLevelOrder(treeNode1);
    }

    public static void zigzagLevelOrder(TreeNode rootNode) {
        // 遍历每一层的方向, true = 正向, false = 逆向
        boolean flag = true;

        // 保存遍历结果
        List<List<TreeNode>> result = new LinkedList<>();
        // 记录每一层待打印的节点
        List<TreeNode> layer = new LinkedList<>();

        Deque<TreeNode> stack = new LinkedList<>();
        stack.add(rootNode);
        Deque<TreeNode> nextStack = new LinkedList<>();

        while (!stack.isEmpty()) {
            TreeNode node = stack.removeLast();
            layer.add(node);
            if (flag) {
                if (node.left != null) {
                    nextStack.add(node.left);
                }
                if (node.right != null) {
                    nextStack.add(node.right);
                }
            } else {
                if (node.right != null) {
                    nextStack.add(node.right);
                }
                if (node.left != null) {
                    nextStack.add(node.left);
                }
            }

            if (stack.isEmpty()) {
                flag = !flag;
                result.add(layer);
                layer = new LinkedList<>();

                stack = nextStack;
                nextStack = new LinkedList<>();
            }
        }

        result.forEach(list -> {
            list.forEach(element -> System.out.print(element.val));
            System.out.println();
        });
    }

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

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

}

输出如下:

1
32
45

你可能感兴趣的:(算法,java,面试,二叉树,遍历)