标签:while 图片 node 节点 mamicode list leetcode solution div
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/** * 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) { Stack<TreeNode> a = new Stack<>(); Stack<TreeNode> b = new Stack<>(); List<List<Integer>> all = new ArrayList<>(); if (root == null) { return all; } a.add(root); boolean flag = true; while (!a.isEmpty() || !b.isEmpty()) { List<Integer> list = new ArrayList<>(); if (flag) { while (!a.isEmpty()) { TreeNode pop = a.pop(); if (pop.left != null) { b.add(pop.left); } if (pop.right != null) { b.add(pop.right); } list.add(pop.val); } all.add(list); flag = false; }else { while (!b.isEmpty()) { TreeNode pop = b.pop(); if (pop.right != null) { a.add(pop.right); } if (pop.left != null) { a.add(pop.left); } list.add(pop.val); } all.add(list); flag = true; } } return all; } }
零分。。。
leetcode 剑指 Offer 32 - III. 从上到下打印二叉树 III
标签:while 图片 node 节点 mamicode list leetcode solution div
原文地址:https://www.cnblogs.com/wangzaiguli/p/14764287.html