【LeetCode】617. 合并二叉树

简介: 【LeetCode】617. 合并二叉树

算法现在就是大厂、外企的硬指标。开发、测开、测试,想往上总是绕不开的。


题目描述


难度:【简单】 标签:【二叉树】


给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。
合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,
否则不为 NULL 的节点将直接作为新二叉树的节点。


题目地址:https://leetcode-cn.com/problems/merge-two-binary-trees/description/


示例


输入: 
  Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
       3
      / \
     4   5
    / \   \ 
   5   4   7


注意: 合并必须从两个树的根节点开始。


解题


合并必须从两个树的根节点开始。按照套路来,首先想好当前节点要做的事情,然后剩下的事情交给递归,不要陷入递归细节。


那么当前传入的 2 个节点,就是相互比较,有 3 种情况:


  • root1 == null && root2 == null,都为空 null,直接返回 null
  • root1 == null || root2 == null,其中一个为 null,返回另一个不为空的节点
  • 剩下就是2个都不为空,那么就把两个值相加,赋值给新的节点


/**
 * 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;
        }
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        // 都不为空,就进行相加,创建一个新的节点
        TreeNode newNode = new TreeNode(root1.val + root2.val);
        // 前序遍历框架部分,分布递归2个节点的左孩子和右孩子
        newNode.left = mergeTrees(root1.left, root2.left);
        newNode.right = mergeTrees(root1.right, root2.right);
        return newNode;
    }
}
相关文章
|
3天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
12 0
|
3天前
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
8 0
|
3天前
leetcode代码记录(二叉树的最小深度
leetcode代码记录(二叉树的最小深度
9 0
|
3天前
leetcode代码记录(二叉树的最大深度
leetcode代码记录(二叉树的最大深度
9 0
|
3天前
leetcode代码记录(翻转二叉树
leetcode代码记录(翻转二叉树
7 0
|
3天前
leetcode代码记录(二叉树的层序遍历
leetcode代码记录(二叉树的层序遍历
12 0
|
3天前
|
算法
leetcode代码记录(二叉树递归遍历
leetcode代码记录(二叉树递归遍历
8 0
|
3天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
3天前
|
算法 API DataX
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
|
3天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”