剑指32.从上到下打印二叉树
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) return new int[0];
ArrayList<Integer> ans = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
ans.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
int[] res = new int[ans.size()];
for (int i = 0; i < ans.size(); i++) {
res[i] = ans.get(i);
}
return res;
}
}
BFS搜索的模板解法。使用队列。
剑指32-2.从上到下打印二叉树2
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
dfs(0,root);
return res;
}
void dfs(int depth, TreeNode root) {
if (root == null) return;
if (res.size() == depth) {
res.add(new ArrayList<>());
}
res.get(depth).add(root.val);
dfs(depth + 1, root.left);
dfs(depth + 1, root.right);
}
}
dfs递归算法的模板解法。
剑指32-3 从上到下打印二叉树3
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
dfs(0, root);
return res;
}
void dfs(int depth, TreeNode root) {
if (root == null) return;
if (res.size() == depth) {
res.add(new ArrayList<>());
}
if (depth % 2 == 0){
res.get(depth).add(root.val);
} else {
res.get(depth).add(0, root.val);
}
dfs(depth + 1, root.left);
dfs(depth + 1, root.right);
}
}
同样是dfs的模板,唯一区别是第二层要倒序添加倒序添加为add(0, root.val)。
剑指26.树的子结构
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
return (A != null && B != null) && (dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B));
}
boolean dfs(TreeNode A, TreeNode B) {
if(B == null) return true;
if(A == null || A.val != B.val) return false;
return dfs(A.left, B.left) && dfs(A.right, B.right);
}
}
dfs搜索,是子结构有三种情况1.相等 2.B是A左子树的 3.B是A的右子树。
剑指27.二叉树的镜像
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}
二叉树左右子树交换,采用递归方法交换方法的固定思路,建立中间变量。之后递归调用mirrorTree函数交换左右子树。
剑指28.对称的二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null ? true : dfs(root.left, root.right);
}
boolean dfs(TreeNode left, TreeNode right) {
if (left == null && right == null) return true;
if (left == null || right == null || left.val != right.val) return false;
return dfs(left.right, right.left) && dfs(left.left, right.right);
}
}
对称二叉树的判断,采用了递归方法,递归调用dfs函数判断left.right和right.right是否相等。