Day 11

zhanglei 2022年08月01日 459次浏览

Day 11

剑指offer 26.树的子结构

题目描述

image-20220801143628318

image-20220801143645921

思路

image-20220801143817413

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if(B == null || A == null)
            return false;
        //遍历A中每个节点,A树中任一节点包含B就能返回true
        return iscontain(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }
    //包含:以A为根的数是否包含B(B必须从A开始)
   public  boolean iscontain(TreeNode A, TreeNode B){
        //如果此时B是空,那么说明B树完成匹配,返回true
        if(B == null)
            return true;
        //如果此时B树不为空,此时A树为空,原B肯定不是原A的子结构
        //如果此时A,B的值不等,那原B肯定不是原A的子结构
        if(A == null || A.val != B.val)
            return false;
        return iscontain(A.left, B.left) && iscontain(A.right, B.right);
    }
}

剑指offer 27.二叉树的镜像

题目描述

image-20220801151754631

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return null;
        //保存 root.right
        TreeNode tem=root.right;
        //先将左子树镜像,再将其赋值给原右子树
        root.right=mirrorTree(root.left);
        //先将由子树镜像,再将其赋值给原左子树
        root.left=mirrorTree(tem);
        return root;
    }
}

剑指offer 28.对称的二叉树

题目描述

image-20220801161602589

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return check(root,root);
    }
    public boolean check(TreeNode p,TreeNode q){
        if(p==null && q==null) return true;
        if(p==null || q==null) return false;
        return p.val==q.val && check(p.left,q.right) && check(p.right,q.left);
    }
}

二叉树相关问题总结

对于递归,不要在意细节,只要在意递归函数的功能就好