LeetCode 617. Merge Two Binary Trees
Main idea of the title:
According to the given binary tree, the values of the corresponding positions are added together to obtain the merged binary tree. (null equals 0)
-Example:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
[3,4,5,5,4,null,7]
The code format given is as follows
/**
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) {
}
}
Thinking analysis
According to the example given in the question, it can be seen that by traversing two binary trees in order, the values of the corresponding positions can be added up.
According to this idea, the initial code can be obtained as follows:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode* t3 = new TreeNode(t1->val+t2->val);
t3->left = mergeTrees(t1->left,t2->left);
t3->right = mergeTrees(t1->right, t2->right);
return t3;
}
However, the code can not handle the case that the binary tree is empty. According to the meaning of the question, when T1 is an empty tree, the return result is the value of t2, and when T2 is an empty tree, the return result is the value of t1.
So the improved code is as follows:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(!t1)
return t2;
if(!t2)
return t1;
TreeNode* t3 = new TreeNode(t1->val+t2->val);
t3->left = mergeTrees(t1->left,t2->left);
t3->right = mergeTrees(t1->right, t2->right);
return t3;
}
Analysis and summary
Similar to LeetCode, this code is improved from the precedent traversal of binary tree, but it has different treatment for space-time of binary tree. If the empty binary tree is not processed, the error will be displayed after running:
Run Code Status: Runtime Error
Line 14: member access within null pointer of type 'struct TreeNode'