一种非线性存储结构,具有存储“一对多”关系的数据元素集合
所有二叉树基本遍历时间复杂度均为:, N代表结点数量。
递归写法
由于前序的特性,他可以展示树结构的继承关系,所以通常前序遍历会用在复制/打印树结构,比如序列化/反序列化,打印文件系统结构。
class Solution {
public List preorderTraversal(TreeNode root) {
List res = new ArrayList<>();
dc(root, res);
return res;
}
private void dc(TreeNode root, List res) {
if (root==null) return;
res.add(root.val);
dc(root.left, res);
dc(root.right, res);
}
}
递归写法
中序遍历最常用就是打印BST结构
class Solution {
List res;
public List inorderTraversal(TreeNode root) {
res = new ArrayList<>();
dc(root);
return res;
}
private void dc(TreeNode root) {
if (root==null) return;
dc(root.left);
res.add(root.val);
dc(root.right);
}
}
后续遍历由于特性是先搜索叶子结点,所以可以用来做一些叶子结点操作(删除叶子结点),还有一些归并操作(计算算术表达式)
class Solution {
public List postorderTraversal(TreeNode root) {
List res = new ArrayList<>();
dc(root, res);
return res;
}
private void dc(TreeNode root, List res) {
if (root==null) return;
dc(root.left, res);
dc(root.right, res);
res.add(root.val);
}
}
树/图类层级遍历直接BFS即可
class Solution {
public List> levelOrder(TreeNode root) {
List> res = new ArrayList<>();
if (root==null) return res;
Queue q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
List tmp = new ArrayList<>();
for (int i=0; i
class Solution {
public List> levelOrderBottom(TreeNode root) {
List> res = new ArrayList<>();
if (root==null) return res;
Queue q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
List tmp = new ArrayList<>();
for (int i=0; i
class Solution {
public List> zigzagLevelOrder(TreeNode root) {
List> res = new ArrayList<>();
dfs(root, 0, res);
return res;
}
private void dfs(TreeNode root, int height, List> res) {
if (root==null) return;
if (res.size()<=height) res.add(new ArrayList<>());
if (height%2==0) {
res.get(height).add(root.val);
} else {
res.get(height).add(0, root.val);
}
dfs(root.left, height+1, res);
dfs(root.right, height+1, res);
}
}
逐列遍历
, N表示dfs遍历时间复杂度,C表示列数,R表示每一列的行数
class Solution {
TreeMap>> colMap;
public List> verticalOrder(TreeNode root) {
if (root==null) return new ArrayList<>();
colMap = new TreeMap<>();
dfs(root, 0, 0);
List> res = new ArrayList<>();
for (int idx: colMap.keySet()) {
Collections.sort(colMap.get(idx), (a, b) -> {
return a.getKey()-b.getKey();
});
List tmp = new ArrayList<>();
for (Pair a: colMap.get(idx)) {
tmp.add(a.getValue());
}
res.add(tmp);
}
return res;
}
private void dfs(TreeNode root, int row, int col) {
if (root==null) return;
colMap.putIfAbsent(col, new ArrayList<>());
colMap.get(col).add(new Pair<>(row, root.val));
dfs(root.left, row+1, col-1);
dfs(root.right, row+1, col+1);
}
}