代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//前序
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
travel(root, list);
return list;
}
public void travel(TreeNode root, List<Integer> list) {
if (root == null)
return;
list.add(root.val);
travel(root.left, list);
travel(root.right, list);
}
}
//中序
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
travel(root, list);
return list;
}
public void travel(TreeNode root, List<Integer> list) {
if (root == null)
return;
travel(root.left, list);
list.add(root.val);
travel(root.right, list);
}
}
//后序
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
travel(root, list);
return list;
}
public void travel(TreeNode root, List<Integer> list) {
if (root == null)
return;
travel(root.left, list);
travel(root.right, list);
list.add(root.val);
}
}