前序遍历
1 | // 递归 |
中序遍历
1 | // 递归 |
后序遍历
1 | // 递归 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// 非递归
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> output = new LinkedList();
Deque<TreeNode> stack = new ArrayDeque();
if (root == null) return output;
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
output.addFirst(root.val);
if (root.left != null) stack.push(root.left);
if (root.right != null) stack.push(root.right);
}
return output;
}
}
层次遍历: BFS
1 | class Solution { |
深度优先遍历DFS -> 前序遍历
1 | class Solution { |