DFS solution,same idea with "Q100. Same Tree"


  • 1
    public class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            TreeNode p1=new TreeNode(0);
            TreeNode p2=new TreeNode(0);
            p1.left=t1;
            p2.left=t2;
            dfs(t1,t2,p1,p2);
            
            return p1.left;
        }
        
        public void dfs(TreeNode t1,TreeNode t2,TreeNode p1,TreeNode p2){
            if(t2==null){
                return;
            }else{
                if(t1==null){
                    if(p2.left==t2){
                        p1.left=t2;
                    }else{
                        p1.right=t2;
                    }
                }else{
                    t1.val+=t2.val;
                    dfs(t1.left,t2.left,t1,t2);
                    dfs(t1.right,t2.right,t1,t2);
                }
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.