rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

617. 合并二叉树 #74

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
/**
 * 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 && root2 == null){
            return null;
        }
        int num = 0;
        if(root1 != null && root2 != null){
            num = root1.val + root2.val;
        }else if(root1 != null){
            num = root1.val;
        }else{
            num = root2.val;
        }
        TreeNode cur = new TreeNode(num);
        cur.left = mergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left);
        cur.right = mergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right);
        return cur;
    }
}