美文网首页
合并二叉树

合并二叉树

作者: 眼若繁星丶 | 来源:发表于2020-09-23 15:07 被阅读0次

    合并二叉树


    LeetCode 617

    https://leetcode-cn.com/problems/merge-two-binary-trees/

    代码如下

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

    相关文章

      网友评论

          本文标题:合并二叉树

          本文链接:https://www.haomeiwen.com/subject/zykoyktx.html