Tree——No.617 Merge Two Binary Trees

Problem:

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.

Explanation:

给定两个二叉树,将其合并,规则是:若两个二叉树结点重合,则相加的值为新树的值,否则就将非空的结点接上。

My Thinking:

使用递归,一共三种情况,第一种是两个结点都非空,即重合,相加保存到t1后返回t1即可;第二种是树1有结点,但树2没有,则直接返回t1;第三种是树2有结点,但树1没有,则直接返回t2;每次递归返回子树的根节点。

My Solution:

class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1==null){
            return t2;
        }else if(t2==null){
            return t1;
        }else{
            t1.val=t1.val+t2.val;
            t1.left=mergeTrees(t1.left,t2.left);
            t1.right=mergeTrees(t1.right,t2.right);
            return t1;
        }
    }         
}

Optimum Thinking:

  1. 同My thinking
  2. 使用栈来实现,首先将根结点入栈,随后分别将左孩子和右孩子两组结点入栈,弹出进行判断,具体见代码注释。

Optimum Solution:

(1)基本同My solution:

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

(2)

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值