LeetCode 100: Same Tree

/**
 * 100. Same Tree
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null) return true;
        if(p==null || q==null) return false;
        return p.val==q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Stack<TreeNode> s = new Stack<>();
        s.push(p);
        s.push(q);
        while(!s.isEmpty()){
            p = s.pop();
            q = s.pop();
            if(p==null && q==null) continue;
            if(p==null || q==null) return false;
            if(p.val != q.val) return false;
            s.push(p.left);
            s.push(q.left);
            s.push(p.right);
            s.push(q.right);
        }
        return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/AAAmsl/p/12800856.html