LeetCode——Find Duplicate Subtrees

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<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        if (root == NULL)
            return vector<TreeNode*>();
        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<string, int>::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<TreeNode*> sub1, res;
    map<string, int> count;
    map<string, TreeNode*> childs;
};
posted @ 2017-09-24 21:24  清水汪汪  阅读(166)  评论(0编辑  收藏  举报