二叉树遍历
二叉树的遍历有四种方式,前序,中序,后序,层序,大多数树相关的算法题都可以通过树的遍历得到解决
1. 前序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public void preOrderTraversal(TreeNode root) { if (root == null) { return; } System.out.print(root.val + " "); preOrderTraversal(root.left); preOrderTraversal(root.right); }
public void preOrderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); while(!stack.isEmpty() || root != null) { if (root != null) { System.out.print(root.val + " "); stack.push(root.right); root = root.left; } else { root = stack.pop(); } } }
|
2. 中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public void inOrderTraversal(TreeNode root) { if (root == null) { return; } inOrderTraversal(root.left); System.out.print(root.val + " "); inOrderTraversal(root.right); }
public void inOrderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); while (!stack.isEmpty() || root != null) { if (root != null) { stack.push(root); root = root.left; } else{ root = stack.pop(); System.out.print(root.val + " "); root = root.right; } } }
|
3. 后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public void postOrderTraversal(TreeNode root) { if (root == null) { return; } postOrderTraversal(root.left); postOrderTraversal(root.right); System.out.print(root.val + " "); }
public void postOrderTraversal(TreeNode root) { Stack<TreeNode> stackTmp = new Stack<TreeNode>(); Stack<TreeNode> ret = new Stack<TreeNode>(); while(!stackTmp.isEmpty() || root != null) { if (root != null) { ret.add(root); stackTmp.add(root.left); root = root.right; } else { root = stackTmp.pop(); } } while(!ret.isEmpty()) { System.out.print(ret.pop().val + " "); } }
|
4. 层序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public void layerTraversal(TreeNode root) { if (root == null) { return; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while ( !queue.isEmpty()) { root = queue.poll(); System.out.print(root.val + " "); if (root.left != null) { queue.offer(root.left); } if (root.right != null) { queue.offer(root.right); } } }
|
5. z形遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); if (root == null) { return ret; } Queue<TreeNode> tree = new LinkedList<>(); tree.offer(root); boolean leftToRight = true; while (!tree.isEmpty()) { int layerSize = tree.size(); ArrayList<Integer> layer = new ArrayList<>(); while (layerSize-- > 0) { root = tree.poll(); layer.add(root.val); if (root.left != null) { tree.offer(root.left); } if (root.right != null) { tree.offer(root.right); } } if (!leftToRight){ Collections.reverse(layer); } leftToRight = !leftToRight; ret.add(layer); } return ret; }
|
LeetCode树相关算法题
剑指offer树相关题目(distinct with leetcode)