LeetCode.M652.寻找重复的子树
题目:
题目大意:
如图所示。
数据范围:
树中的结点数在[1,10^4]范围内。
-200 <= Node.val <= 200
一 、解法 :
思路:
先求出每个节点的高度,然后对相同高度的节点判断是否重复。
代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public HashMap<Integer, List<TreeNode>> layerNodes = new HashMap<>();
public int getLayer(TreeNode root){
if (root == null)
return 0;
int layer = Math.max(getLayer(root.left), getLayer(root.right)) + 1;
List<TreeNode> list = layerNodes.getOrDefault(layer, new ArrayList<>());
list.add(root);
layerNodes.put(layer, list);
return layer;
}
public boolean isCommon(TreeNode nodei, TreeNode nodej){
if (nodei == null && nodej == null)
return true;
if (nodei == null && nodej != null)
return false;
if (nodei != null && nodej == null)
return false;
if (nodei.val != nodej.val)
return false;
return isCommon(nodei.left, nodej.left) && isCommon(nodei.right, nodej.right);
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
getLayer(root);
List<TreeNode> ans = new ArrayList<>();
for (Map.Entry<Integer, List<TreeNode>> lts : layerNodes.entrySet()){
List<TreeNode> nodes = lts.getValue();
int n = nodes.size();
boolean[] used = new boolean[n];
for (int i = 0; i < n; i ++ ){
if (!used[i]){
used[i] = true;
TreeNode nodei = nodes.get(i);
boolean first = true;
for (int j = i + 1; j < n; j ++ ){
if (!used[j]){
TreeNode nodej = nodes.get(j);
if (isCommon(nodei, nodej)){
used[j] = true;
if (first){
ans.add(nodei);
first = false;
}
}
}
}
}
}
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
}
}
时空复杂度分析等:
- 时间复杂度 : O(?)
- 空间复杂度 : O(?)
二 、解法 :
思路:
LeetCode题解:
代码:
class Solution{
HashMap<String, Integer> repeat = new HashMap<>();
List<TreeNode> ans = new ArrayList<>();
public String dfs(TreeNode root){
if (root == null){
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(root.val);
sb.append("(");
sb.append(dfs(root.left));
sb.append(")(");
sb.append(dfs(root.right));
sb.append(")");
String key = new String(sb);
if (repeat.getOrDefault(key, 0) == 1){
ans.add(root);
}
repeat.put(key, repeat.getOrDefault(key,0) + 1);
return key;
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return ans;
}
}
时空复杂度分析等:
-
时间复杂度 : O(n)
-
空间复杂度 : O(n)