请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
好吧,感谢chatgpt给我的帮助,虽然我悲哀地发现,我还没工作,似乎就已经失业了。。。
思路是奇数次添加到末尾,偶数次添加到开头。
递归版本:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) { return new ArrayList<List<Integer>>(); } List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); search(res, queue, true); return res; } private void search(List<List<Integer>> res, Queue<TreeNode> queue, Boolean judge) { List<Integer> list = new ArrayList<>(); if (queue.isEmpty()) { return; } int len = queue.size(); if (judge) { for (int i = 0; i < len; i ++) { TreeNode tem = queue.poll(); list.add(tem.val); if (tem.left != null) { queue.add(tem.left); } if (tem.right != null) { queue.add(tem.right); } } } else { for (int i = 0; i < len; i ++) { TreeNode tem = queue.poll(); list.add(0, tem.val); if (tem.left != null) { queue.add(tem.left); } if (tem.right != null) { queue.add(tem.right); } } } res.add(list); search(res, queue, !judge); } }
非递归优化版本:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) { return new ArrayList<List<Integer>>(); } List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); boolean judge = true; while (!queue.isEmpty()) { List<Integer> list = new ArrayList<>(); int len = queue.size(); for (int i = 0; i < len; i ++) { TreeNode tem = queue.poll(); if (judge) { list.add(tem.val); } else { list.add(0, tem.val); } if (tem.left != null) { queue.add(tem.left); } if (tem.right != null) { queue.add(tem.right); } } res.add(list); judge = !judge; } return res; } }
标签:queue,TreeNode,tem,res,---,add,二叉树,null,III From: https://www.cnblogs.com/allWu/p/17255407.html