zoukankan      html  css  js  c++  java
  • [LeetCode] 617. Merge Two Binary Trees

    You are given two binary trees root1 and root2.

    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 the two trees 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 the new tree.

    Return the merged tree.

    Note: The merging process must start from the root nodes of both trees.

    Example 1:

    Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
    Output: [3,4,5,5,4,null,7]
    

    Example 2:

    Input: root1 = [1], root2 = [1,2]
    Output: [2,2]

    Constraints:

    • The number of nodes in both trees is in the range [0, 2000].
    • -104 <= Node.val <= 104

    合并二叉树。

    给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

    你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/merge-two-binary-trees
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题意是给两个二叉树,请按照 node 的位置对应合并两个二叉树。如果两个二叉树在同一个位置都有各自的 node,就对两个 node 的值相加。

    两种解法,BFS 和 DFS。DFS 解法会用到递归,先序遍历的思路做。

    时间O(n)

    空间O(n)

    JavaScript实现

     1 /**
     2  * @param {TreeNode} t1
     3  * @param {TreeNode} t2
     4  * @return {TreeNode}
     5  */
     6 var mergeTrees = function (t1, t2) {
     7     // corner case
     8     if (t1 === null && t2 === null) {
     9         return null;
    10     }
    11     if (t1 === null || t2 === null) {
    12         return t1 || t2;
    13     }
    14 
    15     // normal case
    16     var root = new TreeNode(t1.val + t2.val);
    17     root.left = mergeTrees(t1.left, t2.left);
    18     root.right = mergeTrees(t1.right, t2.right);
    19     return root;
    20 };

    Java实现

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode() {}
     8  *     TreeNode(int val) { this.val = val; }
     9  *     TreeNode(int val, TreeNode left, TreeNode right) {
    10  *         this.val = val;
    11  *         this.left = left;
    12  *         this.right = right;
    13  *     }
    14  * }
    15  */
    16 class Solution {
    17     public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
    18         // corner case
    19         if (root1 == null) {
    20             return root2;
    21         }
    22         if (root2 == null) {
    23             return root1;
    24         }
    25         
    26         // normal case
    27         root1.val += root2.val;
    28         root1.left = mergeTrees(root1.left, root2.left);
    29         root1.right = mergeTrees(root1.right, root2.right);
    30         return root1;
    31     }
    32 }

    BFS的做法会用到层序遍历,依然还是一个一个 node 扫描。注意需要判断两棵树中是否有空节点,如果有空节点,当前位置的节点值就是另一棵树上那个节点的节点值。

    时间O(n)

    空间O(n)

    JavaScript实现

     1 /**
     2  * @param {TreeNode} t1
     3  * @param {TreeNode} t2
     4  * @return {TreeNode}
     5  */
     6 var mergeTrees = function (t1, t2) {
     7     // corner case
     8     if (t1 === null) return t2;
     9     if (t2 === null) return t1;
    10 
    11     // normal case
    12     let stack = [];
    13     stack.push([t1, t2]);
    14     while (stack.length) {
    15         let cur = stack.pop();
    16         if (cur[0] === null || cur[1] === null) {
    17             continue;
    18         }
    19         cur[0].val += cur[1].val;
    20         if (cur[0].left === null) {
    21             cur[0].left = cur[1].left;
    22         } else {
    23             stack.push([cur[0].left, cur[1].left]);
    24         }
    25         if (cur[0].right === null) {
    26             cur[0].right = cur[1].right;
    27         } else {
    28             stack.push([cur[0].right, cur[1].right]);
    29         }
    30     }
    31     return t1;
    32 };

    Java实现

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode() {}
     8  *     TreeNode(int val) { this.val = val; }
     9  *     TreeNode(int val, TreeNode left, TreeNode right) {
    10  *         this.val = val;
    11  *         this.left = left;
    12  *         this.right = right;
    13  *     }
    14  * }
    15  */
    16 class Solution {
    17     public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
    18         // corner case
    19         if (root1 == null) {
    20             return root2;
    21         }
    22         if (root2 == null) {
    23             return root1;
    24         }
    25 
    26         // normal case
    27         Queue<TreeNode[]> queue = new LinkedList<>();
    28         queue.offer(new TreeNode[] {root1, root2});
    29         while (!queue.isEmpty()) {
    30             TreeNode[] cur = queue.poll();
    31             if (cur[1] == null) {
    32                 continue;
    33             }
    34             cur[0].val += cur[1].val;
    35             if (cur[0].left == null) {
    36                 cur[0].left = cur[1].left;
    37             } else {
    38                 queue.offer(new TreeNode[] { cur[0].left, cur[1].left });
    39             }
    40             if (cur[0].right == null) {
    41                 cur[0].right = cur[1].right;
    42             } else {
    43                 queue.offer(new TreeNode[] { cur[0].right, cur[1].right });
    44             }
    45         }
    46         return root1;
    47     }
    48 }

    LeetCode 题目总结

  • 相关阅读:
    数据驱动编程法
    23个设计模式的简明教程
    分享一篇文章C语言字节对齐问题(适用于C++)转载至http://blog.csdn.net/21aspnet/article/details/6729724
    关于C++类中访问权限的若干疑问(虚函数访问权限)
    利用C# 反射设计支持可扩展插件的应用程序
    隐藏控制台console application窗口
    Intellij IDEA社区版上新建项目或模块没有Spring Initializr选项解决办法
    mac jmeter 界面乱码
    windows 查看端口被占用进程
    php static 变量声明
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12220176.html
Copyright © 2011-2022 走看看