提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣652. 寻找重复的子树
前言
前序位置的代码只能从函数参数中获取父节点传递来的数据,而后序位置的代码不仅可以获取参数数据,还可以获取到子树通过函数返回值传递回来的数据。
一、力扣652. 寻找重复的子树
/*** 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 {List<TreeNode> res;Map<String,Integer> invild;public List<TreeNode> findDuplicateSubtrees(TreeNode root) {res = new LinkedList<>();invild = new HashMap<>();fun(root);return res;}public String fun(TreeNode root){if(root == null){return "#";}String le = fun(root.left);String ri = fun(root.right);String cur = le + "," + ri + "," + root.val;if(invild.getOrDefault(cur,0) == 1){res.add(root);}invild.put(cur,invild.getOrDefault(cur,0)+1);return cur;}
}