剑指offer计划7(搜索与回溯算法简单版)---java

2021/9/7 9:36:09

本文主要是介绍剑指offer计划7(搜索与回溯算法简单版)---java,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.1、题目1

剑指 Offer 26. 树的子结构

1.2、解法

这题看了解法,感叹真的6,代码量减了很多。

(A != null && B != null) && (recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B));

这一句实现了遍历整个树来寻找二叉树,并,同时加上了判断条件。

而recur函数中,则负责判断两个结点下的二叉树是否相同。

当结点移到null的时候,就证明已经结束,并且目前所经过的值都相同,则返回true

这题答案看了之后:“好像我也会。”

过几天一看:“咋做来着。”

1.3、代码

class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        return (A != null && B != null) && (recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B));
    }
    boolean recur(TreeNode A, TreeNode B) {
        if(B == null) return true;
        if(A == null || A.val != B.val) return false;
        return recur(A.left, B.left) && recur(A.right, B.right);
    }
}


2.1、题目2

剑指 Offer 27. 二叉树的镜像

2.2、解法

其实这几行代码还能再简洁一点,因为left和right没变,可以把交换放在下面,

但是你懂就好啦,hhhhh,这题就是递归下去。

2.3、代码

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return null;
        TreeNode left = root.left;
        root.left=root.right;
        root.right=left;
        root.left=mirrorTree(root.left);
        root.right=mirrorTree(root.right);
        return root;
    }
}

3.1、题目3

剑指 Offer 28. 对称的二叉树

3.2、解法

这题自定义函数RECUR,通过判断null或者值不相同返回false,递归解决。

3.3、代码

/**
 * 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) {
        return root==null?true:recur(root.left,root.right);
    }
    boolean recur (TreeNode a,TreeNode b){
        if(a==null && b==null) return true;
        if(a==null || b==null ||a.val!=b.val)  return false;
        return recur(a.left,b.right) && recur(a.right,b.left);
    }
}



这篇关于剑指offer计划7(搜索与回溯算法简单版)---java的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程