Thursday, January 15, 2015

Same Tree (LeetCode Tree)

Question: 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.

Idea: Any order traversal works. I used preorder traversal and use a class member variable to stop the traversal if the trees have been identified as different.

Time: O(n) Space: O(lgn)

Code:
 public class Solution {  
   boolean notSame;  
   public boolean isSameTree(TreeNode p, TreeNode q) {  
     notSame=false;  
     traverse(p,q);  
     return !notSame;  
   }  
   public void traverse(TreeNode p, TreeNode q)  
   {  
     if(notSame==true)  
       return;  
     if(p==null||q==null)  
     {  
       if(p!=null||q!=null)  
         notSame=true;  
       return;  
     }  
     if(p.val!=q.val)  
     {  
       notSame=true;  
       return;  
     }  
     traverse(p.left,q.left);  
     traverse(p.right,q.right);  
   }  
 }  

No comments:

Post a Comment