二叉树结点定义

public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}
}

前序遍历

// Recursive
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}

private void helper(TreeNode root, List<Integer> res) {
if (root != null) {
res.add(root.val);
helper(root.left, res);
helper(root.right, res);
}
}
}

// Iterative
class Solution {
public List<Integer> preorderTraversal1(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);

while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left = null) {
stack.push(cur.left);
}
}
}
}

中序遍历

// Recursive
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
helper(root, res);
return res;
}

private static void helper(TreeNode root, List<Integer> res) {
if (root != null) {
helper(root.left, res);
res.add(root.val);
helper(root.right, res);
}
}
}

// Iterative
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Deque<TreeNode> stack = new ArrayDeque<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}

后序遍历

// Recursive
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}

private static void helper(TreeNode root, List<Integer> res) {
if (root != null) {
helper(root.left, res);
helper(root.right, res);
res.add(root.val);
}
}
}

// Iterative
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
Deque<TreeNode> stack = new ArrayDeque<>();
stack.add(root);

while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.addFirst(cur.val);

if (node.left != null) {
stack.push(cur.left);
}
if (node.right != null) {
stack.push(cur.right);
}
}
return res;
}
}