Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
트리 합치기
풀이:
- 기준이 되는 트리를 하나 선택해서 다른 트리의 값을 기존트리 값에 더한다.
- 재귀 사용
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
//t1 노드가 없으면 t2만 사용
if(t1 == nullptr){
return t2;
}
if(t2==nullptr){
return t1;
}
//t1에 t2값을 더한다.
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 581] Shortest Unsorted Continuous Subarray (0) | 2020.10.11 |
---|---|
[leetcode 543] Diameter of Binary Tree (0) | 2020.10.11 |
[leetcode 55] Jump Game (0) | 2020.10.10 |
[leetcode 406] Queue Reconstruction by Height (0) | 2020.10.10 |
[leetcode 763] Partition Labels (0) | 2020.10.10 |
댓글