Search This Blog

Sunday, December 9, 2012

LeetCode: Same Tree

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.

import java.util.LinkedList; 
 
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        LinkedList<TreeNode> t1 = new LinkedList<TreeNode>(), 
                        t2 = new LinkedList<TreeNode>();
                        
        t1.add(p);
        t2.add(q);
        
        while(!t1.isEmpty() && !t2.isEmpty()){
            TreeNode c1 = t1.poll();
            TreeNode c2 = t2.poll();
            if(c1==null){
                if(c2==null)continue;
                else return false;
            }
            if(c2==null || c1.val!=c2.val) return false;
            t1.add(c1.left);
            t1.add(c1.right);
            t2.add(c2.left);
            t2.add(c2.right);
        }
        return true;
    }
}

1 comment:

Anonymous said...

One minor mistake:
at the end, you'd better check if p1 and p2 have the same size, to eliminate the case where one list is empty while the other is not.

Replace the return with this line
return p1.size() == q1.size();