Advertisement
md5kafka

Untitled

Mar 20th, 2023
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode() {}
  8.  *     TreeNode(int val) { this.val = val; }
  9.  *     TreeNode(int val, TreeNode left, TreeNode right) {
  10.  *         this.val = val;
  11.  *         this.left = left;
  12.  *         this.right = right;
  13.  *     }
  14.  * }
  15.  */
  16. class Solution {
  17.     Set<TreeNode> ans = new HashSet<>();
  18.     public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
  19.         helper(root.left, root.right);
  20.         return new ArrayList(ans);
  21.     }
  22.  
  23.     public boolean helper(TreeNode node1, TreeNode node2) {
  24.         if(node1 == null && node2 == null) {
  25.             return true;
  26.         } else if((node1 == null && node2 != null ) || (node1 != null && node2 == null)) {
  27.             return false;
  28.         }
  29.         boolean answer = false;
  30.         if(node1 != null && node2 != null) {
  31.             if(node1.val == node2.val) {
  32.                 answer = helper(node1.left, node2.left) && helper(node1.right, node2.right);
  33.                 if(answer) {
  34.                     ans.add(node1);
  35.                     return true;
  36.                 }
  37.             }
  38.  
  39.         }
  40.         if(!answer) {
  41.             answer = helper(node1, node2.left) || helper(node1, node2.right);
  42.         }
  43.         if(!answer) {
  44.             answer = helper(node1.left, node2) || helper(node1.right, node2);
  45.         }
  46.         return answer;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement