博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Find Duplicate Subtrees
阅读量:4657 次
发布时间:2019-06-09

本文共 2231 字,大约阅读时间需要 7 分钟。

Question

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.

Solution

遍历所有子树的情况,遍历每棵子树的时候,采用先序遍历,但是得把空节点考虑进去,这样只有结构一样,遍历得到的字符串才一样。 也就是说,先序遍历(不考虑空孩子节点)的结果相同,并不意味着树的结构相同。 但是考虑了以后就是唯一的了。

Code

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector
findDuplicateSubtrees(TreeNode* root) { if (root == NULL) return vector
(); Trace(root); Compare(); return res; } // 遍历所有子树 void Trace(TreeNode* root) { if (root != NULL) sub1.push_back(root); if (root->left != NULL) Trace(root->left); if (root->right != NULL) Trace(root->right); } void Compare() { for (int i = 0; i < sub1.size(); i++) { string tmp = ""; SubTreeStr(sub1[i], tmp); if (count.find(tmp) == count.end()) { count[tmp] = 1; } else count[tmp] += 1; if (childs.find(tmp) == childs.end()) childs[tmp] = sub1[i]; } map
::iterator iter; for (iter = count.begin(); iter != count.end(); iter++) { if (iter->second > 1) res.push_back(childs[iter->first]); } } void SubTreeStr(TreeNode* root1, string& str) { // 考虑空节点,才能保证先序遍历的唯一性 if (root1 == NULL) { str += "NULL"; } else { str += to_string(root1->val); SubTreeStr(root1->left, str); SubTreeStr(root1->right, str); } } vector
sub1, res; map
count; map
childs;};

转载于:https://www.cnblogs.com/zhonghuasong/p/7588731.html

你可能感兴趣的文章
Excel操作之VLOOKUP函数
查看>>
黑盒测试实践--Day4 11.28
查看>>
apache开启rewrite重写
查看>>
反转数字
查看>>
html在图片上实现下雨效果
查看>>
SQL-创建表之前判断表是否存在
查看>>
php spl数据结构
查看>>
Redis 实践3-操作
查看>>
uboot下tftp传输文件
查看>>
计算中文或全角字符串的长度
查看>>
修改xampp的mysql默认密码
查看>>
双指针---反转字符串中的元音字符
查看>>
2015_NJUPT_CTF_Reverse300
查看>>
web自动化测试:watir+minitest(四)
查看>>
Spring MVC整合Velocity
查看>>
关于sublime text
查看>>
js中数组的循环与遍历forEach,map
查看>>
数据分析统计学基础(1)
查看>>
Java ——接口
查看>>
opencv摄像头捕获图像
查看>>