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


求解代码

在【队列】求二叉树的层序遍历的基础上增加一个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;
    }
相关推荐
Navigator_Z5 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2085 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2086 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2086 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解11 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil20813 小时前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu11111114 小时前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表
不会就选b14 小时前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
虚无的纽扣15 小时前
【力扣刷题】第五天:将 x 减到 0 的最小操作数、最大连续1的个数 III
算法·leetcode·职场和发展
hanlin031 天前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode