Day102 | 灵神 | 二叉树 合并二叉树
617.合并二叉树
617. 合并二叉树 - 力扣(LeetCode)
思路:
就是新建一个结点,然后找到左右子树给接上去把该节点返回就是了
接子树的时候有下面几种情况
1.如果root1当前结点不为空,而root2为空的话,那就返回root1作为上层递归函数的结点t的左子树或者右子树
2.如果root2当前结点不为空,而root1为空的话,那就返回root2作为上层递归函数的结点t的左子树或者右子树
3.如果root1当前结点为空,而root2也为空的话,那就返回nullptr
4.如果root1当前结点不为空,而root2也不为空的话,那就把这两个结点的val相加作为当前结点t的val然后返回即可
完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public: TreeNode* tra(TreeNode *t1,TreeNode *t2,TreeNode *t) { if(t==nullptr) t=new TreeNode; if(t1==nullptr&&t2!=nullptr) return t2; else if(t1!=nullptr&&t2==nullptr) return t1; else if(t1==nullptr&&t2==nullptr) return nullptr; else t->val=t1->val+t2->val;
t->left=tra(t1->left,t2->left,t->left); t->right=tra(t1->right,t2->right,t->right); return t; } TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { TreeNode *res=new TreeNode; return tra(root1,root2,res); } };
|
灵神代码:
1 2 3 4 5 6 7 8 9 10
| class Solution { public: TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { if (root1 == nullptr) return root2; if (root2 == nullptr) return root1; return new TreeNode(root1->val + root2->val, mergeTrees(root1->left, root2->left), mergeTrees(root1->right, root2->right)); } };
|