题解 | #树的子结构#
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
import java.util.*; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { private boolean recursion(TreeNode root1, TreeNode root2) { if (root1 == null && root2 != null) return false; //都为空或者root1不为空,root2为空 if (root1 == null || root2 == null) return true; //都不为空 return root1.val == root2.val && recursion(root1.left, root2.left) && recursion(root1.right, root2.right); } public boolean HasSubtree(TreeNode root1, TreeNode root2) { if (root2 == null )return false; if (root1 == null )return false; boolean flag1 = recursion(root1, root2); boolean flag2 = HasSubtree(root1.left, root2); boolean flag3 = HasSubtree(root1.right, root2); return flag1 || flag2 || flag3; } }
看我的!讨厌官网这道题解!这题真的折腾了好久,一直在看官网的思路,他HasSubtree这个方法里面写了三个if条件,冗余了,总共就四种情况搞那么复杂真的是,判断过root2 == null为false后下面的肯定是root2 不为 null了,所以root1 == null的话肯定也false。