跳至主要內容

zigzag遍历


zigzag遍历

题目

给定一棵二叉树,填充一个数组,以逆序表示其逐级遍历,即从最底层(叶子结点所在层)开始遍历,而不是从最高层(根节点所在层)开始遍历。我们应该在单独的子数组中从左到右填充每个级别中所有节点的值。

解答

import java.util.*;

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

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

class ReverseLevelOrderTraversal {
        public static List<List<Integer>> traverse(TreeNode root) {
            List<List<Integer>> result = new LinkedList<List<Integer>>();
            if (root == null)
                return result;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int levelSize = queue.size();
                List<Integer> currentLevel = new ArrayList<>(levelSize);
                for (int i = 0; i < levelSize; i++) {
                    TreeNode currentNode = queue.poll();
                    //添加遍历到的元素的值到currentLevel中
                    currentLevel.add(currentNode.val);
                    //添加当前层的子节点到队列中
                    if (currentNode.left != null)
                        queue.offer(currentNode.left);
                    if (currentNode.right != null)
                        queue.offer(currentNode.right);
                }
                //每次在结果列表的开头添加当前层的元素,而不是末尾
                result.add(0, currentLevel);
            }
            return result;
        }

        public static void main(String[] args) {
            TreeNode root = new TreeNode(12);
            root.left = new TreeNode(7);
            root.right = new TreeNode(1);
            root.left.left = new TreeNode(9);
            root.right.left = new TreeNode(10);
            root.right.right = new TreeNode(5);
            List<List<Integer>> result = ReverseLevelOrderTraversal.traverse(root);
            System.out.println("Reverse level order traversal: " + result);
        }
}
上次编辑于:
贡献者: Neil