[Leetcode]617. Merge Two Binary Trees

本文介绍了一种将两棵二叉树合并的算法,通过迭代和递归两种方式实现。迭代方法采用广度优先搜索(BFS),使用队列同步遍历两棵树,并更新节点值。递归方法则直接对两棵树进行比较和合并。两种方法的时间复杂度均为O(h),空间复杂度为O(n),其中h为最深公共节点深度,n为共同节点数。
部署运行你感兴趣的模型镜像

Iteration solution

In order to merge the 2 binary trees, we need to traverse them in the same pace.
This traverse can be done in BFS or DFS style.
We do it in BFS in this solution.
It is obvious that the key problem here is to maintain the same order of traversal of the 2 trees. And we only want to traverse those nodes that t1 and t2 both have.
For those nodes that only one of them has, simply put the nodes and the entire subtree of the nodes in the corresponding position in the result.
In order to save space, we use t1 as the result, meaning we will modify the nodes in t1 based on traversal status.

The algorithm is showed as following:

  1. Put root of t1 and t2 into queue.
  2. Take one node out from queue1 and queue2 as curr1 and curr2 respectively. Sum up the val (since this is the node that both t1 and t2 have) as the val of the new node at this position.
  3. Check for the left child of curr1 and curr2.
    • If both of them have left child, put left child into the 2 queues respectively.
    • If only one of them has left child or both have no left child, set current result node’s left child as the left child that is not null or null, respectively.
  4. Check for the right child of curr1 and curr2. Do the same checking as step3 above.
  5. Check for if the 2 queue is both empty. If so, stop the loop. Otherwise continue.

The time complexity of this algorithm is O(h) where h is the depth of the deepest common nodes t1 and t2 have.
The space complexity of this O(n) where n is the number of the common nodes of t1 and t2.

Code is showed as following:

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

        Deque<TreeNode> deque1 = new ArrayDeque<>();
        Deque<TreeNode> deque2 = new ArrayDeque<>();

        // BFS
        deque1.offer(t1);
        deque2.offer(t2);

        // Using t1 as the resulting Binary Tree
        while (!deque1.isEmpty() || !deque2.isEmpty()) {
            TreeNode curr1 = deque1.poll();
            TreeNode curr2 = deque2.poll();
            TreeNode result = curr1;
            result.val = curr1.val + curr2.val;

            if (curr1.left == null || curr2.left == null) {
                result.left = curr1.left == null ? curr2.left : curr1.left;
            } else if (curr1.left != null && curr2.left != null) {
                deque1.offer(curr1.left);
                deque2.offer(curr2.left);
            }

            if (curr1.right == null || curr2.right == null) {
                result.right = curr1.right == null ? curr2.right : curr1.right;
            } else if (curr1.right != null  && curr2.right != null) {
                deque1.offer(curr1.right);
                deque2.offer(curr2.right);
            }
        }

        return t1;
    }
}

Recursion solution

Considering the recursion feature of Binary Tree, using recursion to solve this question is straightforward.

If both current TreeNode of t1 and t2 is not null, set the result tree’s current node val as t1.val + t2.val.
Otherwise return the not null one or null.
Recursively do this for t1 and t2’s left and right child.
Time and space complexity is the same as iteration.

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;
    }
}

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值