Wednesday, January 7, 2015

Leetcode – Same Tree



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.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

Solution 1: from  
 
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null){
            return true;
        }else if(p != null && q != null){
            if(p.val == q.val){
                return isSameTree(p.left, q.left) && isSameTree(q.right, p.right);
            }
        }
 
        return false;
    }
}


Solution 2 from zhang lei

1:    bool isSameTree(TreeNode *p, TreeNode *q) {  
2:      if(!p && !q) return true; 
3:      if(!p || !q) return false;
4:      return (p->val == q->val) &&  
5:           isSameTree(p->left, q->left) &&   
6:           isSameTree(p->right, q->right);      
7:    }

Solution 3 from http://blog.csdn.net/xudli/article/details/8557010  (better one)

public boolean isSameTree(TreeNode p, TreeNode q){
  
  LinkedList Tp = new LinkedList<TreeNode>();
  LinkedList Tq = new LinkedList<TreeNode>();
  
  Tp.offer(p);
  Tq.offer(q);
  
  while(!Tp.isEmpty() && !Tq.isEmpty())
  {
   TreeNode x = (TreeNode) Tp.poll();
   TreeNode y = (TreeNode) Tq.poll();
   
   if (x == null){
    if (y != null) return false;
    else continue;
   }
   else{
    if (y == null || x.val != y.val){
     return false;
    }
   }
   Tp.offer(x.left);
   Tp.offer(x.right);
   Tq.offer(y.left);
   Tq.offer(y.right);
  }
  return true;
 }

No comments:

Post a Comment