题解 | #树的子结构#
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
public class Solution { boolean[] res = new boolean[] {false}; public boolean HasSubtree(TreeNode root1, TreeNode root2) { if(root2==null) return false; if (root1 == null) return false; if (compareFromRootNode(root1, root2)) { res[0] = true; } HasSubtree(root1.left, root2); HasSubtree(root1.right, root2); if (res[0]) { return true; } else { return false; } } private boolean compareFromRootNode(TreeNode root1, TreeNode root2) { if (root2 == null) return true; if (root1==null) return false; if (root1.val != root2.val) return false; return compareFromRootNode(root1.left, root2.left) && compareFromRootNode(root1.right, root2.right); } }
缝缝补补的屎山代码