diff --git a/Tree_compare.cpp b/Tree_compare.cpp new file mode 100644 index 0000000..5b8ace7 --- /dev/null +++ b/Tree_compare.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +using namespace std; + +template +class TreeNode { + public: + T data; + vector*> children; + + TreeNode(T data) { this->data = data; } + + ~TreeNode() { + for (int i = 0; i < children.size(); i++) { + delete children[i]; + } + } +}; + +bool areIdentical(TreeNode *root1, TreeNode * root2) +{ + + if(root1 == NULL && root2 == NULL) + { + return false; + } + + if(root1->data == root2->data) + { + return true; + } + + int x = root1->children.size(); + int y = root2->children.size(); + + if(x ==y) + { + for(int i=0;ichildren[i],root2->children[i])) + { + return true; + } + return false; + } + } + else + { + return false; + } +} + +TreeNode* takeInputLevelWise() { + int rootData; + cin >> rootData; + TreeNode* root = new TreeNode(rootData); + + queue*> pendingNodes; + + pendingNodes.push(root); + while (pendingNodes.size() != 0) { + TreeNode* front = pendingNodes.front(); + pendingNodes.pop(); + int numChild; + cin >> numChild; + for (int i = 0; i < numChild; i++) { + int childData; + cin >> childData; + TreeNode* child = new TreeNode(childData); + front->children.push_back(child); + pendingNodes.push(child); + } + } + + return root; +} + +int main() { + TreeNode* root1 = takeInputLevelWise(); + TreeNode* root2 = takeInputLevelWise(); + cout << (areIdentical(root1, root2) ? "true" : "false"); +} \ No newline at end of file diff --git a/Tree_max_child_sum.cpp b/Tree_max_child_sum.cpp new file mode 100644 index 0000000..734d924 --- /dev/null +++ b/Tree_max_child_sum.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +using namespace std; + +template +class TreeNode { + public: + T data; + vector*> children; + + TreeNode(T data) { this->data = data; } + + ~TreeNode() { + for (int i = 0; i < children.size(); i++) { + delete children[i]; + } + } +}; + +TreeNode* maxSumNode(TreeNode* root) { + + if(root==NULL) + { + return NULL; + } + TreeNode *result = root; // root node + int max = root->data; // root node + int childCount = root->children.size(); + for(int i=0; i *temp = maxSumNode(root->children[i]); + if(temp->data > max) + { + max = temp->data; + result = temp; + } + } + return result; +} + +TreeNode* takeInputLevelWise() { + int rootData; + cin >> rootData; + TreeNode* root = new TreeNode(rootData); + + queue*> pendingNodes; + + pendingNodes.push(root); + while (pendingNodes.size() != 0) { + TreeNode* front = pendingNodes.front(); + pendingNodes.pop(); + int numChild; + cin >> numChild; + for (int i = 0; i < numChild; i++) { + int childData; + cin >> childData; + TreeNode* child = new TreeNode(childData); + front->children.push_back(child); + pendingNodes.push(child); + } + } + + return root; +} + +int main() { + TreeNode* root = takeInputLevelWise(); + + TreeNode* ans = maxSumNode(root); + + if (ans != NULL) { + cout << ans->data; + } +} \ No newline at end of file