Leetcode剑指Offer刷题指南:
Leetcode剑指Offer刷题-学习计划目录_DEGv587的博客-CSDN博客
剑指 Offer 26. 树的子结构
解法:递归
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (A == null || B == null) {
return false;
}
return dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
private boolean dfs(TreeNode A, TreeNode B) {
if (B == null) return true;
if (A == null) return false;
return A.val == B.val && dfs(A.left, B.left) && dfs(A.right, B.right);
}
}
剑指 Offer 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;
}
}
剑指 Offer 28. 对称的二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return dfs(root.left, root.right);
}
private boolean dfs(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null) return false;
return root1.val == root2.val && dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
}
}



