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;
    }
}
posted @ 2020-04-29 11:11  AAAmsl  阅读(60)  评论(0编辑  收藏  举报