题解 | #树的子结构#
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { private static boolean IsSame(TreeNode begin,TreeNode beginSub) { if(beginSub == null) { return true; } if(begin == null) { return false; } if(begin.val != beginSub.val) { return false; } return IsSame(begin.left,beginSub.left) && IsSame(begin.right,beginSub.right); } public boolean HasSubtree(TreeNode root1,TreeNode root2) { if(root1 == null || root2 == null) { return false; } boolean ans = false; if(root1.val == root2.val) {//当val值相等,有机会是子结构,此时需要判定左右子树是否相等 ans = IsSame(root1,root2); } if(!ans) {//说明上面判定失败,再看root1的左子树中有没有root2 ans = HasSubtree(root1.left,root2); } if(!ans) {//说明上面判定失败,再看root1的右子树中有没有root2 ans = HasSubtree(root1.right,root2); } return ans; } }