Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode() {}
- * TreeNode(int val) { this.val = val; }
- * TreeNode(int val, TreeNode left, TreeNode right) {
- * this.val = val;
- * this.left = left;
- * this.right = right;
- * }
- * }
- */
- class Solution {
- Set<TreeNode> ans = new HashSet<>();
- public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
- helper(root.left, root.right);
- return new ArrayList(ans);
- }
- public boolean helper(TreeNode node1, TreeNode node2) {
- if(node1 == null && node2 == null) {
- return true;
- } else if((node1 == null && node2 != null ) || (node1 != null && node2 == null)) {
- return false;
- }
- boolean answer = false;
- if(node1 != null && node2 != null) {
- if(node1.val == node2.val) {
- answer = helper(node1.left, node2.left) && helper(node1.right, node2.right);
- if(answer) {
- ans.add(node1);
- return true;
- }
- }
- }
- if(!answer) {
- answer = helper(node1, node2.left) || helper(node1, node2.right);
- }
- if(!answer) {
- answer = helper(node1.left, node2) || helper(node1.right, node2);
- }
- return answer;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement