Java刷题基础版

 为冬奥加油的同时,不要忘了学习哦

目录

1.合并二叉树

2.判断是否为回文字符串


1.合并二叉树

617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/merge-two-binary-trees/submissions/

题目如下:

 解题思路1:(创建一棵新的树来接收)

①特殊情况,当两树均为空,或者其中一棵树为空的情况

②当两树均不为空时的子树递归

代码如下:

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2){
//两棵树均为空的情况
        if(root1==null&&root2==null){
            return null;
}
//只有一棵树为空的情况
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
//创建一棵新的树来进行接收并进行递归
         TreeNode root = new TreeNode(root1.val + root2.val);
        root.left = mergeTrees(root1.left, root2.left);
        root.right = mergeTrees(root1.right, root2.right);
        return root;
    }
}

 解题思路2:(沿用本身存在的树来合并树)

①特殊情况,当两树均为空,或者其中一棵树为空的情况

②当两树均不为空时的子树递归

注意!就是沿用的方法,且沿用后可用前中后序三种方式来进行遍历

代码如下:

//此处用的是前序遍历的方式
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2){
        if(root1==null&&root2==null){
            return null;
}
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        root1.val+=root2.val;
        root1.left= mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right);
        return root1;
    }
}

2.判断是否为回文字符串

判断是否为回文字符串_牛客题霸_牛客网 (nowcoder.com)https://www.nowcoder.com/practice/e297fdd8e9f543059b0b5f05f3a7f3b2?tpId=188&&tqId=38638&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

题目:

解题思路:

①理解回文的含义

②掌握求字符串长度和取得索引位置字符的方法

 public boolean judge(String str) {
        if (str.length() == 0){
            return true;
}else{ int left = 0;
        int right = str.length() - 1;
      while(left<=right){
if(str.charAt(left) != str.charAt(right)) {
          return false;
        }
          left++;
          right--;
      }return true;
      }
    }
}

 

猜你喜欢

转载自blog.csdn.net/weixin_58850105/article/details/122826967