本文主要是介绍【LeetCode刷题-哈希】--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 {Map<String,TreeNode> treeMap = new HashMap<>();Set<String> keySet = new HashSet<>();public List<TreeNode> findDuplicateSubtrees(TreeNode root) {visitTreeNode(root);return new ArrayList<>(treeMap.values());}private String visitTreeNode(TreeNode node){if(node == null){return "";}//将节点的value和它的左子树和右子树节点拼接起来作为keyString treeNodeKey = node.val+"(" + visitTreeNode(node.left)+","+visitTreeNode(node.right)+")";if(!keySet.add(treeNodeKey)){treeMap.put(treeNodeKey,node);}return treeNodeKey;}
}
这篇关于【LeetCode刷题-哈希】--652.寻找重复的子树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!