my three different java solultions


  • 0
    
        public boolean isSameTree(TreeNode p, TreeNode q) {
      // BFS
            Queue<TreeNode> p_queue = new LinkedList<>();
            Queue<TreeNode> q_queue = new LinkedList<>();
            if(p != null) p_queue.offer(p);
            if(q != null) q_queue.offer(q);
    
            while(!p_queue.isEmpty() && !q_queue.isEmpty()){
                TreeNode top_p = p_queue.poll();
                TreeNode top_q = q_queue.poll();
                if(top_p.val != top_q.val){
                   return false;  
                }
                if(top_p.left != null) p_queue.offer(top_p.left);
                if(top_q.left != null) q_queue.offer(top_q.left);
                if(p_queue.size()!= q_queue.size()) return false;
                
                if(top_p.right != null) p_queue.offer(top_p.right);
                if(top_q.right != null) q_queue.offer(top_q.right);
                if(p_queue.size()!= q_queue.size()) return false;
            }
            return p_queue.size() == q_queue.size();
        
        /* DFS
            Stack<TreeNode> p_stack = new Stack<>();
            Stack<TreeNode> q_stack = new Stack<>();
            if(p != null) p_stack.push(p);
            if(q != null) q_stack.push(q);
            while(!p_stack.isEmpty() && !q_stack.isEmpty()){
                TreeNode top_p = p_stack.pop();
                TreeNode top_q = q_stack.pop();
                if(top_p.val != top_q.val){
                    return false;
                }
                if(top_p.right != null) p_stack.push(top_p.right);
                if(top_q.right != null) q_stack.push(top_q.right);
                if(p_stack.size() != q_stack.size()){
                    return false;
                }
                if(top_p.left != null) p_stack.push(top_p.left);
                if(top_q.left != null) q_stack.push(top_q.left);
                if(p_stack.size() != q_stack.size()){
                    return false;
                }
            }
            return p_stack.size() == q_stack.size();*/
        
        
        /* Recursion
            if(p == null && q == null){
                return true;
            }
            if(p == null || q == null){
                return false;
            }
            if(p.val != q.val){
                return false;
            }
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
             
        */}
    

Log in to reply
 

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