24 Merge Two Binary Trees

关注 每天一道编程题 专栏,一起学习进步。

题目

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.

Example 1:

Note: The merging process must start from the root nodes of both 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) {
        
    }
}

分析

题意:给两棵二叉树,将其每个节点相加。

难点:如何同时遍历两棵树的左右子节点

思路一:

  1. 遍历的结束条件是两棵树的当前节点都为空
  2. 新树当前节点值 = (t1.val==null?0:t1.val)+(t2.val==null?0:t2.val)
  3. 新树的左子树 = 递归( 两颗树的左子树)
  4. 新树的右子树 = 递归(两棵树的右子树)

思路二:

  1. 将第一课树作为新树
  2. 如果当前树为空,则返回另一棵树的节点值
  3. 把第二棵树的节点值加到第一棵树的节点上
  4. 第一棵树(新树)的左子树 = 递归( 两颗树的左子树)
  5. 第一棵树(新树)的右子树 = 递归(两棵树的右子树)

解答

法一:

public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1==null && t2==null){
            return null;
        }
        int x = (t1==null?0:t1.val) +(t2==null?0:t2.val);
        TreeNode newNode = new TreeNode(x);
        newNode.left = mergeTrees(t1==null?null:t1.left,t2==null?null:t2.left);
        newNode.right = mergeTrees(t1==null?null:t1.right,t2==null?null:t2.right);
        return newNode;
        
    }
}

法二:

public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
            return t2;
        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;
    }
}
全部评论

相关推荐

今天 15:48
上海交通大学 C++
今天投了小鹏,收到了AI面,大概会问哪些啊?
期末一定及格:总共4个部分,心理测评、行测、然后就是问岗位、对岗位的理解、过往遇到了哪些难点怎么解决,很简单,没有什么特别专业的问题,都是一些综合素质相关的
点赞 评论 收藏
分享
05-24 14:12
门头沟学院 Java
点赞 评论 收藏
分享
05-12 17:00
门头沟学院 Java
king122:你的项目描述至少要分点呀,要实习的话,你的描述可以使用什么技术,实现了什么难点,达成了哪些数字指标,这个数字指标尽量是真实的,这样面试应该会多很多,就这样自己包装一下,包装不好可以找我,我有几个大厂最近做过的实习项目也可以包装一下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务