C++合并两棵二叉树
假设我们有两棵二叉树,并且考虑当我们将其中一棵树覆盖到另一棵树上时,两棵树的一些节点重叠,而其他节点没有重叠。我们必须将它们合并成一棵新的二叉树。合并规则是这样的:如果两个节点重叠,则将节点值相加作为合并节点的新值。否则,非空节点将用作新树的节点。
所以如果树是:
那么输出将是:
为了解决这个问题,我们将遵循以下步骤:
该方法是mergeTrees()。它接受两个树节点n1和n2。它类似于:
如果n1为空,而n2非空,则返回n2,否则当n2为空,而n1非空时,则返回n1,当两者都为空时,则返回null
n1的值 := n1的值 + n2的值
n1的左子树 := mergeTrees(n1的左子树, n2的左子树)
n1的右子树 := mergeTrees(n1的右子树, n2的右子树)
返回n1
示例(C++)
让我们看看下面的实现以更好地理解:
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ temp->left = new TreeNode(val); return; } else{ q.push(temp->left); } if(!temp->right){ temp->right = new TreeNode(val); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr->val == 0){ cout << "null" << ", "; } else{ cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: TreeNode* mergeTrees(TreeNode* n1, TreeNode* n2) { if(!n1 && n2){ return n2; } else if(!n2 && n1)return n1; else if(!n1 && !n2)return NULL; n1->val+=n2->val; n1->left = mergeTrees(n1->left,n2->left); n1->right = mergeTrees(n1->right,n2->right); return n1; } }; main(){ Solution ob; vector<int> v1 = {1,3,2,5}; vector<int> v2 = {2,1,3,NULL,4,NULL,7}; TreeNode *root1 = make_tree(v1); TreeNode *root2 = make_tree(v2); root1 = ob.mergeTrees(root1, root2); tree_level_trav(root1); }
输入
[1,3,2,5] [2,1,3,null,4,null,7]
输出
[3, 4, 5, 5, 4, null, 7, ]
广告