先自定义一下二叉树的类:
// Definition for a binary tree node.
public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) { this.val = val; }TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}
}
一个代码里面同时实现二叉树的前序、中序、后序遍历:
以该二叉树为例
import java.util.ArrayList;
import java.util.List;class PreorderTraversalSolution {public static void main(String[] args) {//构建二叉树TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);root.right.right = new TreeNode(6);Solution sol = new Solution();// 前序、中序、后序System.out.println(sol.preorderTraversal(root).toString()); //[1, 2, 4, 5, 3, 6]System.out.println(sol.inorderTraversal(root).toString()); //[4, 2, 5, 1, 3, 6]System.out.println(sol.postorderTraversal(root).toString()); //[4, 5, 2, 6, 3, 1]}
}class Solution {//前序遍历public List<Integer> preorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();preorder(root, res);return res;}public void preorder(TreeNode root, List<Integer> res) {if (root == null) {return;}res.add(root.val);preorder(root.left, res);preorder(root.right, res);}//中序遍历public List<Integer> inorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();inorder(root, res);return res;}public void inorder(TreeNode root, List<Integer> res) {if (root == null) {return;}inorder(root.left, res);res.add(root.val);inorder(root.right, res);}//后序遍历public List<Integer> postorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();postorder(root, res);return res;}public void postorder(TreeNode root, List<Integer> res) {if (root == null) {return;}postorder(root.left, res);postorder(root.right, res);res.add(root.val);}
}