请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其层次遍历结果:
[ [3], [20,9], [15,7] ]
提示:
节点总数 <= 1000
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> lists = new ArrayList<>(); if(root == null) return lists; Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); boolean lToR = true; s1.push(root); while(!s1.isEmpty() || !s2.isEmpty()){ List<Integer> list = new ArrayList<>(); if(lToR){ while(!s1.isEmpty()){ TreeNode node = s1.pop(); list.add(node.val); if(node.left != null) s2.push(node.left); if(node.right != null) s2.push(node.right); } }else{ while(!s2.isEmpty()){ TreeNode node = s2.pop(); list.add(node.val);
//先添加右节点 if(node.right != null) s1.push(node.right); if(node.left != null) s1.push(node.left); } } lToR = !lToR; lists.add(list); } return lists; } }
原文:https://www.cnblogs.com/zzytxl/p/12634122.html