My stack dsf solution


  • 0
    C
    public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        
        if(p == null && q == null)
            return true;
        if(p == null || q == null)
            return false;
        
        Stack <TreeNode> s1 = new Stack<TreeNode>();
        Stack <TreeNode> s2 = new Stack<TreeNode>();
        s1.add(p);
        s2.add(q);
        
        while(s1.isEmpty() == false && s2.isEmpty() == false){
            TreeNode t1 = s1.pop();
            TreeNode t2 = s2.pop();
            if(t1.val != t2.val){
                return false;
            }
            else{
                if(t1.right != null && t2.right != null){
                    s1.add(t1.right);
                    s2.add(t2.right);
                }
                if(t1.left != null && t2.left != null){
                    s1.add(t1.left);
                    s2.add(t2.left);
                }
                if ((t1.right != null && t2.right == null)||(t1.right == null && t2.right != null)||(t1.left == null && t2.left != null)||(t1.left != null && t2.left == null)){
                    return false;
                }
            }
        }
        return true;
    }
    

    }


Log in to reply
 

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