前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >24 Merge Two Binary Trees

24 Merge Two Binary Trees

作者头像
devi
发布2021-08-18 16:02:11
2110
发布2021-08-18 16:02:11
举报
文章被收录于专栏:搬砖记录

题目

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.

代码语言:javascript
复制
/**
 * 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. 第一棵树(新树)的右子树 = 递归(两棵树的右子树)

解答

法一:

代码语言:javascript
复制
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;
        
    }
}

法二:

代码语言:javascript
复制
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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/02/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 解答
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档