1 前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
order(root, res);
return res;
}
private void order(TreeNode root, List<Integer> res) {
if (root == null) return;
res.add(root.val);
order(root.left, res);
order(root.right, res);
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if (root == null) return res;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node == null) continue;
res.add(node.val);
stack.push(node.right);
stack.push(node.left);
}
return res;
}
}
2 后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
order(root, res);
return res;
}
private void order(TreeNode root, List<Integer> res) {
if (root == null) return;
order(root.left, res);
order(root.right, res);
res.add(root.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if (root == null) return res;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node == null) continue;
res.add(node.val);
stack.push(node.left);
stack.push(node.right);
}
Collections.reverse(res);
return res;
}
}
3 中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
order(root, res);
return res;
}
private void order(TreeNode root, List<Integer> res) {
if (root == null) return;
order(root.left, res);
res.add(root.val);
order(root.right, res);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if (root == null) return res;
Deque<TreeNode> stack = new LinkedList<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
res.add(node.val);
root = node.right;
}
return res;
}
}
4 层序遍历
class Solution {
public List<Integer> sequenceOrder(TreeNode root) {
List<Integer> res = new LinkedList<Integer>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
int cnt = queue.size();
for (int i = 0; i < cnt; i++) {
TreeNode node = queue.poll();
res.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return res;
}
}