zoukankan      html  css  js  c++  java
  • 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;
    };
    
  • 相关阅读:
    js 遇到问题
    table 排序 添加 删除 等操作
    json对象
    .style, .getComputedStyle(),.currentStyle区别
    3个div 宽度移入移出时变化
    运动 js
    OWASP Top 10之文件上传漏洞简析(二)
    owasp top10 之文件上传漏洞简析
    前台实现ajax 需注意的地方
    apache-Rewrite重写规则配置
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7588731.html
Copyright © 2011-2022 走看看