合并两个二叉树
遞歸法
class Solution { public:TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {if(root1==nullptr) return root2;if(root2==nullptr) return root1;TreeNode* root=new TreeNode(0);root->val=root1->val+root2->val;root->left=mergeTrees(root1->left,root2->left);root->right=mergeTrees(root1->right,root2->right);return root;} };迭代法
和對稱二叉樹那道題解題思路一致,就是求?叉樹對稱的時(shí)候就是把兩個(gè)樹的節(jié)點(diǎn)同時(shí)加?隊(duì)列進(jìn)??較。
class Solution { public:TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {if(root1==nullptr) return root2;if(root2==nullptr) return root1;queue<TreeNode*> que;que.push(root1);que.push(root2);while(!que.empty()){TreeNode* root1=que.front(); que.pop();TreeNode* root2=que.front(); que.pop();//此時(shí)兩個(gè)節(jié)點(diǎn)?定不為空,val相加root1->val=root1->val+root2->val; //如果兩棵樹左節(jié)點(diǎn)都不為空,加?隊(duì)列if(root1->left&&root2->left) {que.push(root1->left);que.push(root2->left);}//如果兩棵樹右節(jié)點(diǎn)都不為空,加?隊(duì)列if(root1->right&&root2->right){que.push(root1->right);que.push(root2->right);}//當(dāng)root1的左節(jié)點(diǎn)為空root2左節(jié)點(diǎn)不為空,就賦值過去if(root1->left==nullptr&&root2->left) { root1->left=root2->left;} //當(dāng)root1的右節(jié)點(diǎn)為空root2右節(jié)點(diǎn)不為空,就賦值過去if(root1->right==nullptr&&root2->right) { root1->right=root2->right;}}return root1;} };迭代法中,?般?起操作兩個(gè)樹都是使?隊(duì)列模擬層序遍歷,同時(shí)處理兩個(gè)樹的節(jié)點(diǎn),這種?式最好理解,如果?模擬遞歸的思路的話,要復(fù)雜?些。
總結(jié)