这题看了解法,感叹真的6,代码量减了很多。
(A != null && B != null) && (recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B));
这一句实现了遍历整个树来寻找二叉树,并,同时加上了判断条件。
而recur函数中,则负责判断两个结点下的二叉树是否相同。
当结点移到null的时候,就证明已经结束,并且目前所经过的值都相同,则返回true
这题答案看了之后:“好像我也会。”
过几天一看:“咋做来着。”
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);
    }
}
其实这几行代码还能再简洁一点,因为left和right没变,可以把交换放在下面,
但是你懂就好啦,hhhhh,这题就是递归下去。
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;
    }
}
这题自定义函数RECUR,通过判断null或者值不相同返回false,递归解决。
/**
 * 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);
    }
}
原文:https://www.cnblogs.com/urmkhaos/p/15236736.html