二叉树的锯齿形层序遍历 (Binary Tree Zigzag Level Order Traversal)

 

思路:本质还是bfs,只是要注意这个顺序

// @Title: 二叉树的锯齿形层序遍历 (Binary Tree Zigzag Level Order Traversal)
// @Author: qisiii
// @Date: 2024-01-14 19:51:40
// @Runtime: 1 ms
// @Memory: 40.8 MB
// @comment: 本质还是bfs,只是要注意这个顺序
// @flag: WHITE
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList();
        if (root == null) {
            return result;
        }
        result.add(new ArrayList(Arrays.asList(root.val)));
        List<TreeNode> rootList = new ArrayList();
        rootList.add(root);
        bfs(rootList, result, false);
        return result;
    }

    void bfs(List<TreeNode> queue, List<List<Integer>> result, boolean order) {
        if (queue == null || queue.size() <= 0) {
            return;
        }
        List<TreeNode> temp = new ArrayList();
        List<Integer> level = new ArrayList();
        for (int i = 0; i < queue.size(); i++) {
            TreeNode node;
            //取值是反序
            if (order) {
                node = queue.get(i);
                if (node.left != null) {
                    level.add(node.left.val);
                }
                if (node.right != null) {
                    level.add(node.right.val);
                }
            } else {
                node = queue.get(queue.size() - i - 1);
                if (node.right != null) {
                    level.add(node.right.val);
                }
                if (node.left != null) {
                    level.add(node.left.val);
                }
            }
            //存放都是正序
            if (queue.get(i).left != null) {
                temp.add(queue.get(i).left);
            }
            if (queue.get(i).right != null) {
                temp.add(queue.get(i).right);
            }

        }
        if (level.size() > 0) {
            result.add(level);
        }
        bfs(temp, result, !order);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18