Simple Iterative java solution using Stack


#1

public TreeNode solve(TreeNode A, TreeNode B) {
Stack s = new Stack<>();
s.push(B);s.push(A);
while(!s.empty()){
TreeNode x=s.pop();
TreeNode y=s.pop();
x.val=x.val+y.val;
if(x.right!=null&y.right!=null){s.push(y.right);s.push(x.right);}
else if(x.right==null){x.right=y.right;}
//else if(y.right==null), then no need to change x.right
if(x.left!=null&y.left!=null){s.push(y.left);s.push(x.left);}
else if(x.left==null){x.left=y.left;}
//else if(y.leftt==null), then no need to change x.left
}
return A;
}