二叉树合并

二叉树合并

LeetCode 617

题目链接
对于二叉树的合并,想把一颗树直接插入到另一颗树上
一般遍历二叉树,无返回值

public void Add(TreeNode t1) {
	if(t1 == null)
		reutrn;
	Add(t1.left);
	Add(t2.right);
}

因为做的题太少,就容易受已知思想的禁锢,在写这个题的时候,也想套用这个模式。一开始想直接插入,把出口列好就行了,但是总是没控制好指针导致递归到空地址
设想出口:

  • t2 为空 (即t2不会对t1产生影响
  • t1 原本分支为空则返回

为了避免指针指向空,且插入将t2分支插入t1故用辅助节点记录父节点,用flag区分左孩子还是右孩子,但是t2为空时影响flag的值,造成情况比较复杂。显然这样写不仅需要预判,而且还需要把所有情况都预判到,造成操作复杂,违背算法设计的目的
比如

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    static int flag = 0,flag2 = 0;
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null) {
            return t2;
        }
        Add(t1,t2);
        return t1;
    }
    public void Add(TreeNode t1, TreeNode t2) {
        
        if(t2 != null && t1 != null){
            t1.val += t2.val;
            flag = 0;
            if(t1.left == null) {
                t1.left = t2.left;
                flag = 1;
            }
            if(t1.right == null) {
                t1.right = t2.right;
                if(flag == 1) {
                    return;
                }   
            }
            if(flag != 1)
                Add(t1.left,t2.left);
            Add(t1.right,t2.right);
        }
    }  
}

这个是还是欠缺考虑 左子树不为空,右子树却为空的情况,如果有同学想到的解决方案,欢迎请多指教。
当然,如果使用空返回值,可以考虑将t1,t2增添到一颗新树上,在进入递归时加入限制条件,且对递归的参数加以判断。

比较好的解题思路

采用返回值为节点类 直接遍历二叉树
出口:

更新t1

  • t1为空,返回t2
  • t2为空,返回t1

最终出口 退出函数

  • t1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null)
            return t2;
        Add(t1,t2);
        return t1;
    }
    public TreeNode Add(TreeNode t1, TreeNode t2) {
        if(t1 == null)
            return t2;
        if(t2 == null)
            return t1;
        t1.val += t2.val;
        t1.left = Add(t1.left,t2.left);
        t1.right = Add(t1.right,t2.right);
        return t1;
    }
}
发布了6 篇原创文章 · 获赞 1 · 访问量 357

猜你喜欢

转载自blog.csdn.net/qq_43461153/article/details/103330272