|
| 1 | +package com.leetcode_cn.medium; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/***********二叉树的锯齿形层次遍历*********/ |
| 7 | +/** |
| 8 | + * 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 |
| 9 | + * |
| 10 | + * 例如: |
| 11 | + * |
| 12 | + * 给定二叉树 [3,9,20,null,null,15,7], |
| 13 | + * |
| 14 | + * 3 |
| 15 | + * |
| 16 | + * / \ |
| 17 | + * |
| 18 | + * 9 20 |
| 19 | + * |
| 20 | + * / \ |
| 21 | + * |
| 22 | + * 15 7 |
| 23 | + * |
| 24 | + * 返回锯齿形层次遍历如下: |
| 25 | + * |
| 26 | + * [ [3], [20,9], [15,7] ] |
| 27 | + * |
| 28 | + * @author ffj |
| 29 | + * |
| 30 | + */ |
| 31 | +public class BinaryTreeZigzagLevelOrderTraversal { |
| 32 | + |
| 33 | + public class TreeNode { |
| 34 | + int val; |
| 35 | + TreeNode left; |
| 36 | + TreeNode right; |
| 37 | + |
| 38 | + TreeNode(int x) { |
| 39 | + val = x; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * 层次遍历 |
| 45 | + * |
| 46 | + * @param root |
| 47 | + * @return |
| 48 | + */ |
| 49 | + public List<List<Integer>> zigzagLevelOrder(TreeNode root) { |
| 50 | + if (root == null) |
| 51 | + return new ArrayList<>(); |
| 52 | + |
| 53 | + List<Integer> nodes = new ArrayList<>(); |
| 54 | + List<Integer> nodesTemp; |
| 55 | + List<TreeNode> tns = new ArrayList<>(); |
| 56 | + List<TreeNode> tnsTemp; |
| 57 | + List<List<Integer>> nodeList = new ArrayList<>(); |
| 58 | + nodes.add(root.val); |
| 59 | + tns.add(root); |
| 60 | + nodeList.add(nodes); |
| 61 | + // 初始从右开始 |
| 62 | + boolean left = false; |
| 63 | + while (true) { |
| 64 | + tnsTemp = new ArrayList<>(); |
| 65 | + nodesTemp = new ArrayList<>(); |
| 66 | + if (!left) {// 从右边开始 |
| 67 | + for (int i = tns.size() - 1; i >= 0; i--) { |
| 68 | + TreeNode node = tns.get(i); |
| 69 | + if (node.right != null) { |
| 70 | + tnsTemp.add(node.right); |
| 71 | + nodesTemp.add(node.right.val); |
| 72 | + } |
| 73 | + if (node.left != null) { |
| 74 | + tnsTemp.add(node.left); |
| 75 | + nodesTemp.add(node.left.val); |
| 76 | + } |
| 77 | + } |
| 78 | + left = true; |
| 79 | + } else { |
| 80 | + // 从左边开始 |
| 81 | + for (int i = tns.size() - 1; i >= 0; i--) { |
| 82 | + TreeNode node = tns.get(i); |
| 83 | + if (node.left != null) { |
| 84 | + tnsTemp.add(node.left); |
| 85 | + nodesTemp.add(node.left.val); |
| 86 | + } |
| 87 | + if (node.right != null) { |
| 88 | + tnsTemp.add(node.right); |
| 89 | + nodesTemp.add(node.right.val); |
| 90 | + } |
| 91 | + } |
| 92 | + left = false; |
| 93 | + } |
| 94 | + tns = new ArrayList<>(); |
| 95 | + nodes = new ArrayList<>(); |
| 96 | + tns.addAll(tnsTemp); |
| 97 | + nodes.addAll(nodesTemp); |
| 98 | + if (nodes.size() == 0) |
| 99 | + break; |
| 100 | + nodeList.add(nodes); |
| 101 | + } |
| 102 | + return nodeList; |
| 103 | + } |
| 104 | + |
| 105 | +} |
0 commit comments