LeetCode merged binary tree

1. Title

Insert picture description here

2. Ideas (description in Java language)

Take the t1 node as the root node, modify the pointer in place and
return the exit condition recursively

  1. If one of the nodes is not empty, return the non-empty node
  2. Modify the pointer on the original tree of t1
  3. Both are empty, return t1 directly
/**
 * 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&&t2!=null){
    
    
            t1.val+=t2.val;
            mergeTrees(t1.left,t2.left);
            mergeTrees(t1.right,t2.right);
            if(t1.left == null&&t2.left!=null){
    
    
                t1.left = t2.left;
            }
            if(t1.right==null&&t2.right!=null){
    
    
                t1.right=t2.right;
            }
            return t1;
        }
        if(t1==null&&t2!=null){
    
    
            return t2;
        }
        if(t1!=null&&t2==null){
    
    
            return t1;
        }
        return t1;
    }
}

Time complexity T(N), space complexity O(1)

Guess you like

Origin blog.csdn.net/weixin_43967679/article/details/108760061