合并二叉树

import java.util.LinkedList;

/***
 * 已知两颗二叉树,将它们合并成一颗二叉树。
 * 合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。例如:
 * 两颗二叉树是:
 * Tree 1
 *      1
 *     / \
 *    3   2
 *   /
 *  5
 *
 * Tree 2
 *    2
 *   / \
 *  1   3
 *   \   \
 *    4   7
 *
 * 合并后的树为
 *     3
 *    / \
 *   4   5
 *  / \    \
 * 5  4    7
 *
 * 核心思路:
 * 同时遍历A、B两颗树,
 * 如果两颗树节点都不为空,则值相加,递归左右节点
 */
public class NC117 {

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

    /**
     * 非递归 
     * @param t1
     * @param t2
     * @return
     */
    public TreeNode mergeTrees1 (TreeNode t1, TreeNode t2) {
        if(t1 == null){
            return t2;
        }
        if (t2 == null){
            return t1;
        }
        LinkedList<TreeNode> linkedList = new LinkedList<>();
        linkedList.add(t1);
        linkedList.add(t2);
        while (!linkedList.isEmpty()){
            TreeNode a1 = linkedList.poll();
            TreeNode a2 = linkedList.poll();
            a1.val = a1.val + a2.val;
            if (a1.left != null && a2.left != null){
                linkedList.add(a1.left);
                linkedList.add(a2.left);
            }else if (a1.left == null){
                a1.left = a2.left;
            }
            
            if (a1.right != null && a2.right != null){
                linkedList.add(a1.right);
                linkedList.add(a2.right);
            }else if (a1.right == null){
                a1.right = a2.right;
            }
        }
        return t1;
    }

}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页