leetcode 65: Same Tree

Same TreeSep 3 '12

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.

 bad one recursive.

/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(p==null && q==null) return true;
        else if( p==null || q==null) return false;
        if( p.val != q.val) return false;
        else return isSameTree( p.left, q.left) && isSameTree(p.right, q.right);
        
    }
}


 

good one iterative.

public class Solution {
    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;
    }
}


 

posted @ 2013-01-30 17:05  西施豆腐渣  阅读(98)  评论(0编辑  收藏  举报