617. Merge Two Binary Trees

来源:互联网 发布:手机屏幕镜像软件 编辑:程序博客网 时间:2024/06/08 02:43

  找工作时,刷leetcode完全是为了找工作,但却发现解题很有乐趣,现在已经入职,也坚持着刷算法题,希望能不断成长,最终成为技术牛。

  这道题是一道通过率很高的easy题,实在没什么难度。读完题目,就知道又是树形结构的变形。

 1.题目

     

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:

Input: Tree 1                     Tree 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  Output: Merged tree:     3    / \   4   5  / \   \  5   4   7

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

2.题目分析

   数据结构为二叉树的算法题,很多时候可以采用递归的解法,因为这种数据结构本身就是递归定义。所以我们只需要处理好边界以及递归结束条件,就能够递归得出最终结果,但是如果追求O(n)时间效率,可以进行优化,比如在递归基础上实现尾递归,或者借助于栈这种特殊数据结构进行解题,降低时间开销。

3.解题代码(仅仅参考)

public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        // 边界、递归结束处理
        if(t1==null){
            return t2;
        }
        if(t2==null){
            return t1;
        }
        if(t1==null&&t2==null){
            return t1;
        }
        TreeNode node = new TreeNode(t1.val+t2.val);
        node.left = mergeTrees(t1.left,t2.left);  // 采用递归方法
        node.right = mergeTrees(t1.right,t2.right);
        
        return node;
    }
}

4.总结

   可以在解题后,多多思考解题思路,以及在时间,空间开销上优化。并参考别人解题思路,对比自己的解题思路,吸取优点,改掉自己解题缺点,不断进步。

    

原创粉丝点击