Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/652.html
652. Find Duplicate Subtrees (Medium)
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1 / \ 2 3 / / \ 4 2 4 / 4
The following are two duplicate subtrees:
2 / 4
and
4
Therefore, you need to return above trees’ root in the form of a list.
Companies:
Uber, Amazon, Google, Microsoft
Related Topics:
Tree
Similar Questions:
- Serialize and Deserialize Binary Tree (Hard)
- Serialize and Deserialize BST (Medium)
- Construct String from Binary Tree (Easy)
Solution 1.
-
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<TreeNode> findDuplicateSubtrees(TreeNode root) { List<TreeNode> duplicateList = new ArrayList<TreeNode>(); if (root == null) return duplicateList; Set<String> visitedSet = new HashSet<String>(); Set<String> duplicateSet = new HashSet<String>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); String str = treeToString(node); if (!visitedSet.add(str) && duplicateSet.add(str)) duplicateList.add(node); TreeNode left = node.left, right = node.right; if (left != null) queue.offer(left); if (right != null) queue.offer(right); } return duplicateList; } public String treeToString(TreeNode root) { List<String> list = new ArrayList<String>(); list.add(String.valueOf(root.val)); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); TreeNode left = node.left, right = node.right; if (left != null) { list.add(String.valueOf(left.val)); queue.offer(left); } else list.add("null"); if (right != null) { list.add(String.valueOf(right.val)); queue.offer(right); } else list.add("null"); } return list.toString(); } } ############ /** * 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 { private Map<String, Integer> counter; private List<TreeNode> ans; public List<TreeNode> findDuplicateSubtrees(TreeNode root) { counter = new HashMap<>(); ans = new ArrayList<>(); dfs(root); return ans; } private String dfs(TreeNode root) { if (root == null) { return "#"; } String v = root.val + "," + dfs(root.left) + "," + dfs(root.right); counter.put(v, counter.getOrDefault(v, 0) + 1); if (counter.get(v) == 2) { ans.add(root); } return v; } }
-
// OJ: https://leetcode.com/problems/find-duplicate-subtrees/ // Time: O(N^2) since string concatenation takes O(N) time on average // Space: O(N^2) since string take O(N) space on average class Solution { unordered_map<string, int> cnt; vector<TreeNode*> ans; string dfs(TreeNode *node) { if (!node) return "#"; auto s = to_string(node->val) + "," + dfs(node->left) + "," + dfs(node->right); if (++cnt[s] == 2) ans.push_back(node); return s; } public: vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { dfs(root); return ans; } };
-
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findDuplicateSubtrees( self, root: Optional[TreeNode] ) -> List[Optional[TreeNode]]: def dfs(root): if root is None: return '#' v = f'{root.val},{dfs(root.left)},{dfs(root.right)}' counter[v] += 1 if counter[v] == 2: ans.append(root) return v ans = [] counter = Counter() dfs(root) return ans ############ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findDuplicateSubtrees(self, root): from hashlib import sha256 def hash_(x): S = sha256() S.update(x) return S.hexdigest() def merkle(node): if not node: return '#' m_left = merkle(node.left) m_right = merkle(node.right) node.merkle = hash_(m_left + str(node.val) + m_right) count[node.merkle].append(node) return node.merkle count = collections.defaultdict(list) merkle(root) return [nodes.pop() for nodes in count.values() if len(nodes) >= 2]
-
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findDuplicateSubtrees(root *TreeNode) []*TreeNode { var ans []*TreeNode counter := make(map[string]int) var dfs func(root *TreeNode) string dfs = func(root *TreeNode) string { if root == nil { return "#" } v := strconv.Itoa(root.Val) + "," + dfs(root.Left) + "," + dfs(root.Right) counter[v]++ if counter[v] == 2 { ans = append(ans, root) } return v } dfs(root) return ans }
-
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> { const map = new Map<string, number>(); const res = []; const dfs = (root: TreeNode | null) => { if (root == null) { return '#'; } const { val, left, right } = root; const s = `${val},${dfs(left)},${dfs(right)}`; map.set(s, (map.get(s) ?? 0) + 1); if (map.get(s) === 2) { res.push(root); } return s; }; dfs(root); return res; }
-
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; impl Solution { fn dfs( root: &Option<Rc<RefCell<TreeNode>>>, map: &mut HashMap<String, i32>, res: &mut Vec<Option<Rc<RefCell<TreeNode>>>>, ) -> String { if root.is_none() { return String::from('#'); } let s = { let root = root.as_ref().unwrap().as_ref().borrow(); format!( "{},{},{}", root.val.to_string(), Self::dfs(&root.left, map, res), Self::dfs(&root.right, map, res) ) }; *map.entry(s.clone()).or_insert(0) += 1; if *map.get(&s).unwrap() == 2 { res.push(root.clone()); } return s; } pub fn find_duplicate_subtrees( root: Option<Rc<RefCell<TreeNode>>>, ) -> Vec<Option<Rc<RefCell<TreeNode>>>> { let mut map = HashMap::new(); let mut res = Vec::new(); Self::dfs(&root, &mut map, &mut res); res } }