You are given two binary trees root1 and root2.
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 the two trees 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 the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
https://leetcode.com/problems/merge-two-binary-trees/
Merge Two Binary Trees - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
두 트리의 합을 구해 새 트리를 만드는 문제이다.
그래도 아이디어까진 얼추 맞힌 것 같다.
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null) return root2;
if(root2 == null) return root1;
TreeNode root3 = new TreeNode(root1.val + root2.val);
root3.left = mergeTrees(root1.left, root2.left);
root3.right = mergeTrees(root1.right, root2.right);
return root3;
}
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 733. Flood Fill (0) | 2022.07.09 |
---|---|
LeetCode 116. Populating Next Right Pointers in Each Node (0) | 2022.07.07 |
LeetCode 763. Partition Labels (0) | 2022.07.04 |
LeetCode 22. Generate Parentheses (0) | 2022.06.30 |
LeetCode 160. Intersection of Two Linked Lists (0) | 2022.06.29 |