Java solution without recursive method


  • 0
    A

    Breadthfirst traversal, merge nodes.

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            
        Queue<TreeNode> queue1 = new LinkedList();
        Queue<TreeNode> queue2 = new LinkedList();
        if(t1==null)return t2;
        if(t2==null)return t1;
    
        queue1.add(t1);
        queue2.add(t2);
    
        while (!queue1.isEmpty() || !queue1.isEmpty()) {
          TreeNode node1 = queue1.poll();
          TreeNode node2 = queue2.poll();
          if (node1 != null && node2 != null)
            node1.val += node2.val;
            
          if (node1.left != null && node2.left != null) {
            queue1.add(node1.left);
            queue2.add(node2.left);
          }else if(node1.left == null && node2.left != null){
            node1.left=node2.left;
            node2.left=null;
          }
    
          if (node1.right != null && node2.right != null) {
            queue1.add(node1.right);
            queue2.add(node2.right);
          }else if(node1.right == null && node2.right != null){
            node1.right=node2.right;
            node2.right=null;
          }
        }
        return t1;
      
            
        }
    

Log in to reply
 

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