Fork me on GitHub

【数据结构】算法 Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层序遍历

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

给一个二叉树的root,返回其节点值从上到下遍历,奇数层从左到右 遍历,偶数层从右到左。

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
/**
 * 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>> ans = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        if(root ==null){
            return ans;
        }
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> arr = new ArrayList<>();
            int length = queue.size();
            for(int i =0;i<length;i++){
                TreeNode n = queue.poll();
                if(n.left!=null){
                    queue.add(n.left);
                }
                if(n.right!=null){
                    queue.add(n.right);
                }
                arr.add(n.val);
            }         
            ans.add(arr);
        }
        int size = ans.size();      
        for(int i =0;i<size;i++){
            if(i%2==1){                
                Collections.reverse(ans.get(i));               
            }
        }
        return ans;
    }
}

Tag

tree BFS

posted @ 2021-04-23 09:23  WilliamCui  阅读(67)  评论(0编辑  收藏  举报