LeetCode-Same Tree(java)

34 篇文章 0 订阅

作者:disappearedgod

时间:2014-5-14

题目

Same Tree

  Total Accepted: 16148  Total Submissions: 38995 My Submissions

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.


解法

首先,要对空树判断。
其次,要知道什么是相同,什么是不同。
  • 值不等是不同
  • 空和非空是不同
最后要注意,如果你选择的是堆栈或队列方法的话,需要对输入进行判断:特别地,当两棵并不相同的树的非空情况相同的情况的考虑(【1,2】【1,#,2】)。

java

迭代

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p!=null&&q!=null){
            if(p.val==q.val )
                return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
            else
                return false;
            
        }
        else if(p==null&&q==null)
            return true;
        else 
            return false;
    }
}

队列(java)

其一
public boolean isSameTree(TreeNode p, TreeNode q) {
         Queue<TreeNode> pQueue = new LinkedList<TreeNode>();
         Queue<TreeNode> qQueue = new LinkedList<TreeNode>();
         if(p!=null) pQueue.offer(p);
         if(q!=null) qQueue.offer(q);
         while(!pQueue.isEmpty() && !qQueue.isEmpty()){
             TreeNode pp = pQueue.poll();
             TreeNode qq = qQueue.poll();
             //if(pp==null && qq==null)                return true;
             //else if(pp==null || qq==null)                return false;
             if(pp!=null && qq!=null){
                 if(pp.val!=qq.val)
                    return false;
                    
                //if(pp.left!=null)
                    pQueue.offer(pp.left);
                //if(qq.left!=null)
                    qQueue.offer(qq.left);
                //if(pp.right!=null)
                    pQueue.offer(pp.right);
                //if(qq.right!=null)
                    qQueue.offer(qq.right);
             }
             else if(pp==null && qq==null){
                 continue;
             }
             else return false;
         }
         
         if(pQueue.isEmpty() && qQueue.isEmpty())            return true;
         else            return false;
    }

其二
考虑两棵树并不是同等地位:一棵树是比对的目标,而另一棵树是比较的对象。
比较的对象一旦不同于比较目标就返回错。
但是,比较完成后才能返回正确。
public boolean isSameTree(TreeNode p, TreeNode q) {
         Queue<TreeNode> pQueue = new LinkedList<TreeNode>();
         Queue<TreeNode> qQueue = new LinkedList<TreeNode>();
         if(p!=null) pQueue.offer(p);
         if(q!=null) qQueue.offer(q);
         while(!pQueue.isEmpty() && !qQueue.isEmpty()){
             TreeNode pp = pQueue.poll();
             TreeNode qq = qQueue.poll();
             // pp  null null pp  pp    (target)
             // qq  null qq   qq  null
             if(pp==null ){
                 if(qq!=null)
                        return false;
                 else
                    continue;
             }
             
             if(qq==null || (qq.val!=pp.val))
                return false;
             pQueue.offer(pp.left);
             qQueue.offer(qq.left);
             pQueue.offer(pp.right);
             qQueue.offer(qq.right);
        }
        if(pQueue.isEmpty() && qQueue.isEmpty())            return true;
         else            return false;
    }


其三
改错,这里入队的时候“对于空的查看”其实是不对的。
public boolean isSameTree(TreeNode p, TreeNode q) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Queue<TreeNode> q1 = new LinkedList<TreeNode>();
        Queue<TreeNode> q2 = new LinkedList<TreeNode>();
                       
        q1.offer(p);
        q2.offer(q);
        
        while( !q1.isEmpty() && !q2.isEmpty() ) {
            TreeNode x = q1.poll();
            TreeNode y = q2.poll();
            
            if(x==null) {
                if( y!=null) return false;
                else continue;
            }
            
            if(y==null || x.val!=y.val) return false;
            
            q1.offer( x.left);
            q1.offer( x.right);
            q2.offer(y.left);
            q2.offer(y.right);
        }
        
        return true;
    }

总结

对于一般的方法来说,队列可能就是像C++一样使用,单纯的pop(), push()即可。
譬如我们使用如下的代码
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        queue<TreeNode*> q1;
        queue<TreeNode*> q2;
        
        q1.push(p);
        q2.push(q);
        
        while(!q1.empty() && !q2.empty()){
            TreeNode* n1 = q1.front();
            TreeNode* n2 = q2.front();
            q1.pop();
            q2.pop();
            
            if(n1==nullptr && n2==nullptr) continue;
            if(n1==nullptr || n2==nullptr) return false;
            
            if( n1->val != n2->val) return false;
            
            q1.push(n1->left);
            q1.push(n1->right);
            q2.push(n2->left);
            q2.push(n2->right);
            
        }
        
        return q1.empty() && q2.empty();
    }
};

我们这里参考看一下JDK7中的定义
Modifier and Type Method and Description
boolean add(E e)
Inserts the specified element into this queue if it is possible to do so immediately
without violating capacity restrictions, returning  true upon success and throwing 
an  IllegalStateException if no space is currently available.
E element()
Retrieves, but does not remove, the head of this queue.
boolean offer(E e)
Inserts the specified element into this queue if it is possible to do so immediately 
without violating capacity restrictions.
E peek()
Retrieves, but does not remove, the head of this queue, or returns  null if this
 queue is empty.
E poll()
Retrieves and removes the head of this queue, or returns  null if this queue is 
empty.
E remove()
Retrieves and removes the head of this queue.
我们发现了,除了java中常用的add之外,offer(E e)操作时候做两件事情:插入队尾或者返回false;另外这里选择pull()它移除了队列或者返回null.
我们没有使用element()或者remove()因为会抛出NoSuchElementException的异常。
另外peek和element都是不移除情况下返回。

参考

leetcode 65: Same Tree









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值