Leetcode_103_二叉树的锯齿形层序遍历_数据结构

12/22

挺水的一道二叉树遍历,
无非就是用一个变量来判断一下目前应该是从左往右还是从右往左
然后存储到Deque里
package com;

import java.util.*;

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

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

class Solution {
    
    
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    
    
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
    
    
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = true;
        while (!queue.isEmpty()) {
    
    
            Deque<Integer> temp = new LinkedList<>();
            int n = queue.size();
            for (int i = 0; i < n; i++) {
    
    
                TreeNode tn = queue.poll();
                if (flag) {
    
    
                    temp.addLast(tn.val);
                } else {
    
    
                    temp.addFirst(tn.val);
                }
                if (tn.left != null) {
    
    
                    queue.offer(tn.left);
                }
                if (tn.right != null) {
    
    
                    queue.offer(tn.right);
                }
            }
            flag = !flag;
            ans.add(new LinkedList<>(temp));
        }
        return ans;
    }
}

/**
 * @author Riter
 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        Solution a = new Solution();

    }
}

猜你喜欢

转载自blog.csdn.net/HDUCheater/article/details/111504437