在 C++ 中查詢所有重複的子樹


考慮我們有一個二叉樹。我們需要查詢樹中是否存在一些重複的子樹。假設我們有一個如下所示的二叉樹 -

有兩個大小為 2 的相同子樹。在每個子樹 D 中,BD 和 BE 也是重複的子樹。我們可以透過使用樹序列化和雜湊處理來解決這個問題。我們將在雜湊表中儲存子樹的中序遍歷。我們將為葉節點插入開括號和閉括號。

示例

 線上演示

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;
const char MARKER = '$';
struct Node {
   public:
   char data;
   Node *left, *right;
};
Node* getNode(char key) {
   Node* newNode = new Node;
   newNode->data = key;
   newNode->left = newNode->right = NULL;
   return newNode;
}
unordered_set<string> subtrees;
string inorder(Node* node, unordered_map<string, int>& map) {
   if (!node)
   return "";
   string str = "(";
   str += inorder(node->left, map);
   str += to_string(node->data);
   str += inorder(node->right, map);
   str += ")";
   if (map[str] == 1)
      cout << node->data << " ";
   map[str]++;
   return str;
}
void duplicateSubtreeFind(Node *root) {
   unordered_map<string, int> map;
   inorder(root, map);
}
int main() {
   Node *root = getNode('A');
   root->left = getNode('B');
   root->right = getNode('C');
   root->left->left = getNode('D');
   root->left->right = getNode('E');
   root->right->right = getNode('B');
   root->right->right->right = getNode('E');
   root->right->right->left= getNode('D');
   duplicateSubtreeFind(root);
}

輸出

D E B

更新於: 24-10-2019

150 次瀏覽

啟動你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.