二叉树的遍历
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }
前序遍历
递归版
private void getPreTree(TreeNode node, List<Integer> list) { if (node == null) { return; } //zhong 左右 list.add(node.val); if (node.left != null) { getPreTree(node.left, list); } if (node.right != null) { getPreTree(node.right, list); } }
中序遍历
递归版
private void getMidTree(TreeNode node, List<Integer> list) { if (node == null) { return; } //左中右 if (node.left != null) { getMidTree(node.left, list); } list.add(node.val); if (node.right != null) { getMidTree(node.right, list); } }
后序遍历
递归版
private void getAfterTree(TreeNode node, List<Integer> list) { if (node == null) { return; } //左右中 if (node.left != null) { getAfterTree(node.left, list); } if (node.right != null) { getAfterTree(node.right, list); } list.add(node.val); }