[Java] Leetcode 652. Find Duplicate Subtrees [Binary Tree #10]

Поділитися
Вставка
  • Опубліковано 25 лис 2024

КОМЕНТАРІ • 8

  • @suryateja6780
    @suryateja6780 2 роки тому +1

    What is that chrome extension you are using to draw/write on the tab?

  • @pengx9000
    @pengx9000 Рік тому

    I'm a little bit confused about this: if we do post-order traversal, why we first append the curNode val (line 44), then append left subtree, last right subtree (15:00), shouldn't be (Left, Right, CurNode)?

    • @ovidiubalaban2466
      @ovidiubalaban2466 Рік тому

      It doesn't matter because it's just a String representation which is used to compare values, and it's the same if the CurNode is at the start or at end, you could try it and you will see that it works in both ways. What it does matter is to execute first, the leftNode, then the rightNode, and then to return the curSubtree.

  • @MeetManga
    @MeetManga 2 роки тому

    Another solution,the time complexity and space complexity is also N², but the code is shorter, enjoy:
    class Solution {
    Map map = new HashMap();
    List res = new LinkedList();
    public List findDuplicateSubtrees(TreeNode root) {
    String path = "";
    dfs(root, path);
    return res;
    }
    private String dfs(TreeNode root, String path){
    if(root == null) return "#";
    path += String.join(",", String.valueOf(root.val),
    dfs(root.left, path),
    dfs(root.right, path));
    map.put(path, map.getOrDefault(path, 0) + 1);
    if(map.get(path) == 2){
    res.add(root);
    }
    return path;
    }
    }

  • @xuebindong4803
    @xuebindong4803 2 роки тому +1

    love you

  • @diwyanshukanthwal8669
    @diwyanshukanthwal8669 2 роки тому

    why inorder will not work on this

    • @austing.8682
      @austing.8682 2 роки тому

      Because you need the left serialization and the right serialization before you can create a complete a serialization for the current node.

    • @rahulmg05
      @rahulmg05 2 роки тому

      @@austing.8682 Isn't that true for pre order and post order as well ?