본문 바로가기
[PS] 문제풀이/LeetCode

617. Merge Two Binary Trees ( LeetCode / JAVA / 안산학생 )

by 안산학생 2021. 9. 12.

617. 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

 

 

 


 

문제풀이

 - 모든 합계는 root1에 저장한다.

 - root1, root2 전위 순회 하며 root1에 값을 저장한다.

 

 


 

 

코드

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null) return root2;
        if(root2 == null) return root1;
        root1.val += root2.val;
        root1.left = mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right);
        return root1;
    }
}

 

 


 

 

회고

 - LeetCode의 함수형 PS가 아직 적응되지 않는다...

댓글