【Leetcode 617】Merge Two Binary Trees -EASY

【Leetcode 617】Merge Two Binary Trees - EASY

题目

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.

给出两个二叉树,当你用其中一棵二叉树覆盖另外一棵树时,一些结点会重叠,一些不会。
你需要将这两棵树合并成一棵树。合并规则是如果两颗树的对应结点重合,则将两结点的值的和作为新结点的值。如果不重合,则非空结点将被作为新树的新结点。


示例:
在这里插入图片描述


Notes: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) {
        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;
    }
}

在这里插入图片描述

反思

复杂度分析

时间复杂度:O(n)
空间复杂度:
O(n)(最差情形下)
O(log n)(平均情形下)

思路反思

太久没有做算法题,大脑一片混沌。递归呀!最简单的递归呀!!竟然没有第一时间想出来。

扩展

考虑不使用递归来遍历二叉树。

如何遍历呢?我们开辟一块栈空间用来存放结点对。

首先将两棵二叉树的根结点对放到栈stack中。

接下来是一个循环,每次循环从栈中取出一个结点对,如果两结点任一为空,则continue;否则,将两结点的值相加的结果赋给结点1。(因为二叉树1是我们最终想要的新的二叉树。)如果结点1的左子结点或右子结点为空,则将结点2的左子节点或右子结点赋给结点1,否则,则将该结点对加到stack中。

循环结束的条件是栈为空,此时所有的结点对都被访问到并被处理。

/**
 * 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;
        Stack <TreeNode[]> stack = new Stack<>();
        stack.push(new TreeNode[]{t1,t2});
        while(!stack.isEmpty()){
            TreeNode[] t = stack.pop();
            if(t[0]==null||t[1]==null){
                continue;
            }
            t[0].val+=t[1].val;
            if(t[0].left == null){
                t[0].left = t[1].left;
            }else{
                stack.push(new TreeNode[]{t[0].left,t[1].left});
            }
            if(t[0].right == null){
                t[0].right = t[1].right;
            }else{
                stack.push(new TreeNode[]{t[0].right,t[1].right});
            }
        }
        return t1;
    }
}

在这里插入图片描述
时间复杂度:O(n)
空间复杂度:O(n)

使用额外的栈空间来对二叉树进行遍历的方法是我第一次遇到的,对我的思路是一个扩展,很值得学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值