public List<List<Integer>> zigzagLevelOrder(TreeNode root) { if (root == null) returnnew ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); Stack<TreeNode> rightStack = new Stack<>(); Stack<TreeNode> leftStack = new Stack<>(); rightStack.push(root); while (!rightStack.isEmpty() || !leftStack.isEmpty()) { TreeNode p; List<Integer> list = new ArrayList<>(); while (!rightStack.isEmpty()) { p = rightStack.pop(); list.add(p.val); if (p.left != null) leftStack.push(p.left); if (p.right != null) leftStack.push(p.right); } if (!list.isEmpty()) { res.add(list); list = new ArrayList<>(); } while (!leftStack.isEmpty()) { p = leftStack.pop(); list.add(p.val); if (p.right != null) rightStack.push(p.right); if (p.left != null) rightStack.push(p.left); } if (!list.isEmpty()) res.add(list); } return res; }
从底向上层次遍历二叉树:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public List<List<Integer>> levelOrderBottom(TreeNode root) { if (root == null) returnnew ArrayList<>(); ArrayDeque<TreeNode> queue = new ArrayDeque<>(); List<List<Integer>> ans = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); LinkedList<Integer> level = new LinkedList<>(); for (int i = 0; i < size; i++) { TreeNode pNode = queue.poll(); if (pNode.left != null) queue.offer(pNode.left); if (pNode.right != null) queue.offer(pNode.right); level.add(pNode.val); } ans.add(0, level); } return ans; }