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


求解代码

【队列】求二叉树的层序遍历的基础上增加一个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;
    }
相关推荐
tachibana22 小时前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
不能跑的代码不是好代码3 小时前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特3 小时前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
YuK.W17 小时前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
旖-旎19 小时前
《LeetCode 64 最小路径和 || LeetCode 174 地下城游戏》
c++·算法·leetcode·动态规划
凯瑟琳.奥古斯特20 小时前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
凯瑟琳.奥古斯特1 天前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111111 天前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表
人道领域1 天前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
旖-旎2 天前
《LeetCode 746 使用最小花费爬楼梯 || LeetCode 91 解码方法》
c++·算法·leetcode·动态规划