
递归
/**
* 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:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode* root=NULL;
construct(root,t1,t2);
return root;
}
void construct(TreeNode* &root, TreeNode* t1, TreeNode* t2){
if(t1||t2){
root=new TreeNode((t1?t1->val:0)+(t2?t2->val:0));
construct(root->left,t1?t1->left:NULL,t2?t2->left:NULL);
construct(root->right,t1?t1->right:NULL,t2?t2->right:NULL);
}
}
};
本文介绍了一种使用递归算法合并两个二叉树的方法。通过创建一个新的二叉树节点,将两个输入树中相应节点的值相加,并递归地处理左右子树,实现了树的合并。此方法适用于树结构的融合场景。
1142

被折叠的 条评论
为什么被折叠?



