系列文章目录
剑指offer练习
今天是简单的搜索与回溯算法
思路:首先想好B树是A树子结构的判断条件,即节点值相等且左右子树一样。用递归解决
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);
}
public 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);
}
思路:对每个节点来说,交换其左右节点。递归出口是root=null,首先把左右结点镜像,再交换左右节点。
public TreeNode mirrorTree(TreeNode root) {
if (root == null)
return null;
TreeNode node = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(node);
return root;
}
思路:结合上题镜像条件。root1左节点与root2相等,且root1右节点和root2左节点相等,则对称。
public boolean isSymmetric(TreeNode root) {
if (root==null)
return true;
return isEqual(root.left,root.right);
}
public boolean isEqual(TreeNode root1,TreeNode root2){
if (root1==null && root2==null)
return true;
if (root1==null || root2==null)
return false;
return root1.val==root2.val && isEqual(root1.left,root2.right) && isEqual(root1.right,root2.left);
}
额外做了一道,感觉自己的方法好笨
2570. 合并两个二维数组 - 求和法
思路:两个指针t1、t2分别指向两个数组,比较二者指向的元素,按不同情况分别处理。注意:定义存储结果的数组时,元素最多为2*max(nums1.length,nums2.length),或者简单起见定义为400(规定数组长度最长为200)。最后的结果数组,应该剔除空元素。
class Solution {
public int[][] mergeArrays(int[][] nums1, int[][] nums2) {
int nums[][] = new int[400][2];
int t1=0,t2=0,i=0;
while (t1<nums1.length && t2<nums2.length){
if (nums1[t1][0]<nums2[t2][0]){
nums[i][0]=nums1[t1][0];
nums[i][1]=nums1[t1][1];
i++;
t1++;
}else if (nums1[t1][0]==nums2[t2][0]){
nums[i][0]=nums1[t1][0];
nums[i][1]=nums1[t1][1]+nums2[t2][1];
i++;
t1++;
t2++;
}else {
nums[i][0]=nums2[t2][0];
nums[i][1]=nums2[t2][1];
i++;
t2++;
}
}
if (t1<nums1.length){//nums1没有遍历完
while (t1<nums1.length){
nums[i][0]=nums1[t1][0];
nums[i][1]=nums1[t1][1];
i++;
t1++;
}
}
if (t2<nums2.length){
while (t2<nums2.length){
nums[i][0]=nums2[t2][0];
nums[i][1]=nums2[t2][1];
i++;
t2++;
}
}
int count=0;
for (int j=0;j<nums.length;j++){
if (nums[j][0]!=0&&nums[j][1]!=0)
count++;
}
int results[][] = new int[count][2];
for (int j=0;j<count;j++){
results[j][0]=nums[j][0];
results[j][1]=nums[j][1];
}
return results;
}
}