|
| 1 | +##### 题目 |
| 2 | + |
| 3 | +``` |
| 4 | +给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 |
| 5 | +
|
| 6 | +例如: |
| 7 | +给定二叉树 [3,9,20,null,null,15,7], |
| 8 | +
|
| 9 | + 3 |
| 10 | + / \ |
| 11 | + 9 20 |
| 12 | + / \ |
| 13 | + 15 7 |
| 14 | +
|
| 15 | +返回锯齿形层次遍历如下: |
| 16 | +
|
| 17 | +[ |
| 18 | + [3], |
| 19 | + [20,9], |
| 20 | + [15,7] |
| 21 | +] |
| 22 | +``` |
| 23 | +#### 代码 |
| 24 | +##### 两个栈 |
| 25 | + |
| 26 | +``` |
| 27 | +class Solution { |
| 28 | + public List<List<Integer>> zigzagLevelOrder(TreeNode root) { |
| 29 | + List<List<Integer>> resList=new ArrayList<>(); |
| 30 | + Stack<TreeNode> stack1=new Stack<>(); |
| 31 | + Stack<TreeNode> stack2=new Stack<>(); |
| 32 | + if (root==null) { |
| 33 | + return resList; |
| 34 | + } |
| 35 | +
|
| 36 | + stack1.push(root); |
| 37 | + int index=1; |
| 38 | + while(!stack1.isEmpty() || !stack2.isEmpty()){ |
| 39 | + int length1=stack1.size(); |
| 40 | + int length2=stack2.size(); |
| 41 | + List<Integer> tempList=new ArrayList<>(); |
| 42 | + if (index%2!=0) { |
| 43 | + for (int i=0; i<length1; i++) { |
| 44 | + if (stack1.peek().left!=null) { |
| 45 | + stack2.push(stack1.peek().left); |
| 46 | + } |
| 47 | + if (stack1.peek().right!=null) { |
| 48 | + stack2.push(stack1.peek().right); |
| 49 | + } |
| 50 | + tempList.add(stack1.pop().val); |
| 51 | + } |
| 52 | + index++; |
| 53 | + }else{ |
| 54 | + for (int i=0; i<length2; i++) { |
| 55 | + if (stack2.peek().right!=null) { |
| 56 | + stack1.push(stack2.peek().right); |
| 57 | + } |
| 58 | + if (stack2.peek().left!=null) { |
| 59 | + stack1.push(stack2.peek().left); |
| 60 | + } |
| 61 | + tempList.add(stack2.pop().val); |
| 62 | + } |
| 63 | + index++; |
| 64 | + } |
| 65 | + |
| 66 | + resList.add(tempList); |
| 67 | + } |
| 68 | + return resList; |
| 69 | + } |
| 70 | +} |
| 71 | +``` |
| 72 | +##### 递归 |
| 73 | + |
| 74 | +``` |
| 75 | +class Solution { |
| 76 | + public List<List<Integer>> zigzagLevelOrder(TreeNode root) { |
| 77 | + List<List<Integer>> res=new ArrayList<>(); |
| 78 | + zigzagLevelOrderHelp(res,root,0); |
| 79 | + return res; |
| 80 | + } |
| 81 | +
|
| 82 | + public void zigzagLevelOrderHelp(List<List<Integer>> res,TreeNode root,int index){ |
| 83 | + if (root==null) return; |
| 84 | +
|
| 85 | + if (res.size()<=index) { |
| 86 | + res.add(new ArrayList<>()); |
| 87 | + } |
| 88 | + if (index%2==0) { |
| 89 | + res.get(index).add(root.val); |
| 90 | + }else{ |
| 91 | + res.get(index).add(0,root.val); |
| 92 | + } |
| 93 | + zigzagLevelOrderHelp(res,root.left,index+1); |
| 94 | + zigzagLevelOrderHelp(res,root.right,index+1); |
| 95 | + } |
| 96 | +} |
| 97 | +``` |
| 98 | +> add(index,int) 该函数可以对一个数组进行前序插入 其余的会往后挪动 |
0 commit comments