2015年8月7日 星期五

LEET code--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.


檢查兩個樹 有沒有完全一致(結構上跟val)


bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if( p==NULL && q == NULL)return true;
    if( p==NULL && q!= NULL )return false;
    if( p!=NULL && q==NULL)return false;
    if(p->val != q->val)return false;
   
    bool le,ri;
    le=isSameTree(p->left,q->left);
    ri=isSameTree(p->right, q->right);
   
    return (le==false || ri==false)? false:true;
   
}



更好的寫法:
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p == NULL && q == NULL) 
    return true;
if(p != NULL && q == NULL) 
    return false;
if(p == NULL && q != NULL) 
    return false;
if(p->val != q->val)
    return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}

直接用&& 改回傳只有true的方式  比較簡潔

沒有留言:

張貼留言