前序遍历
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>(16);
if (null == root) {
return res;
}
List<Integer> lRes = preorderTraversal(root.left);
List<Integer> rRes = preorderTraversal(root.right);
res.add(root.val);
res.addAll(lRes);
res.addAll(rRes);
return res;
}
另一种写法: 使用栈进行迭代
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>(16);
if (null == root) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
if (null != node.right) {
stack.push(node.right);
}
if (null != node.left) {
stack.push(node.left);
}
res.add(node.val);
}
return res;
}
中序遍历
常见写法 递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
List<Integer> left = inorderTraversal(root.left);
List<Integer> right = inorderTraversal(root.right);
result.addAll(left);
result.add(root.val);
result.addAll(right);
return result;
}
另一种写法: 使用栈进行迭代
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while(current != null) {
stack.add(current);
current = current.left;
}
current = stack.pop();
result.add(current.val);
current = current.right;
}
return result;
}
后序遍历
常见递归写法
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
List<Integer> left = postorderTraversal(root.left);
List<Integer> right = postorderTraversal(root.right);
result.addAll(left);
result.addAll(right);
result.add(root.val);
return result;
}
使用栈进行迭代
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node.right == null && node.left == null) {
result.add(stack.pop().val);
}
if (node.right != null) {
stack.push(node.right);
node.right = null;
}
if (node.left != null) {
stack.push(node.left);
node.left = null;
}
}
return result;
}