【队列】按之字形顺序打印二叉树


求解代码

【队列】求二叉树的层序遍历的基础上增加一个flag区分奇偶性就行。

java 复制代码
public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();

		if(pRoot==null){
			return ans;
		}
		Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
		queue.add(pRoot);

		boolean flag = true;

		while(!queue.isEmpty()){
			ArrayList<Integer> list = new ArrayList<>();

			int n = queue.size();

			flag = !flag;

			for(int i=0;i<n;i++){
				TreeNode cur = queue.poll();
				list.add(cur.val);

				if (cur.left!=null) {
					queue.add(cur.left);
				}
				
				if(cur.right!=null){
					queue.add(cur.right);
				}
			}

			if(flag){
				Collections.reverse(list);
			}
			ans.add(list);
		}

		return ans;
    }
相关推荐
普贤莲花10 小时前
【2026年第18周---写于20260501】---舍得
程序人生·算法·leetcode
m0_6294947310 小时前
LeetCode 热题 100-----16.除了自身以外数组的乘积
数据结构·算法·leetcode
We་ct11 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划
无敌昊哥战神11 小时前
【LeetCode 37】解数独 (Sudoku Solver) —— 回溯法详解 (Python/C/C++)
c语言·c++·python·算法·leetcode
风筝在晴天搁浅11 小时前
LeetCode 162.寻找峰值
算法·leetcode
罗超驿12 小时前
双指针算法经典案例:LeetCode 283. 移动零(Java详解)
java·算法·leetcode
人道领域12 小时前
【数据结构与算法分析】二叉树面试通关手册:遍历图解 · 分类对比 · 代码模板
数据结构·算法·leetcode·深度优先
水蓝烟雨12 小时前
2901. 最长相邻不相等子序列 II
算法·leetcode
承渊政道12 小时前
【动态规划算法】(回文串问题解题框架与经典案例)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
We་ct17 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript