当前位置:   article > 正文

leetcode之按之字形顺序打印二叉树_之字形打印二叉树leetcode

之字形打印二叉树leetcode

题目:

给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}


该二叉树之字形层序遍历的结果是

[

[1],

[3,2],

[4,5]

]

思路:比照层序遍历的方法。

        这里使用两个栈来实现存储每层节点。答案要求分层输出,是一个二维数组的形式,所以对于其中的一层来说,先利用stack1中的数据(这是上一层遍历时存到栈中的这一层的值)存到list中,然后按照层数分辨出左右子节点先后顺序,把数据存到stack2中。这一层遍历完成后,stack1中成为空的,这是将stack2和stack1互换,继续进行循环。

        外层循环条件是stack1是否为空,即判断层数,里层循环同样是stack1是否为空,但是这个意义是这一层中的节点是否为空!注意这两个意义不一样!

代码:

  1. import java.util.*;
  2. /*
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }
  11. */
  12. public class Solution {
  13. public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
  14. ArrayList<ArrayList<Integer>> res = new ArrayList<>();
  15. if(pRoot == null)
  16. return res;
  17. Stack<TreeNode> stack1 = new Stack<>();
  18. Stack<TreeNode> stack2 = new Stack<>();
  19. int layer = 0;
  20. stack1.push(pRoot);
  21. while(!stack1.isEmpty()){
  22. ArrayList<Integer> amp = new ArrayList<>();
  23. layer++;
  24. res.add(amp);
  25. while(!stack1.isEmpty()){
  26. TreeNode temp = stack1.pop();
  27. if(layer % 2 == 1){
  28. if(temp.left != null){
  29. stack2.push(temp.left);
  30. }
  31. if(temp.right != null){
  32. stack2.push(temp.right);
  33. }
  34. }else if(layer % 2 == 0){
  35. if(temp.right != null){
  36. stack2.push(temp.right);
  37. }
  38. if(temp.left != null){
  39. stack2.push(temp.left);
  40. }
  41. }
  42. }
  43. res.add(amp);
  44. Stack<TreeNode> s = stack2;
  45. stack2 = stack1;
  46. stack1 = s;
  47. }
  48. return res;
  49. }
  50. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/837113
推荐阅读
相关标签
  

闽ICP备14008679号