• 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;
    };
    
  • 相关阅读:
    难得之货,令人行妨
    Oracle死锁
    log4j杂记
    Oracle9或11使用了Oracle10的驱动引起的时间丢失
    程序员要重视过劳
    oracle提供的有用函数(待续)
    Mysql扩展之replication概述
    @autowired与@qualifer的使用区别备忘
    Oracle中的in参数的个数限制
    java版正则式提取替换示例
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7588731.html
Copyright © 2020-2023  润新知