Thursday, May 22, 2014

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.


The solution is trivial, just check it recursively.

C++ Code:

/*
 * func: same_tree
 * goal: to check if two input trees are the same
 * @param p: root node of tree 1
 * @param q: root node of tree 2
 * return: true or false
 */
bool same_tree(TreeNode *p, TreeNode *q){
    if(p == nullptr){
        return q == nullptr;
    }
    if(q == nullptr){
        return p == nullptr;
    }
    
    if(p->val == q->val){
        return same_tree(p->left, q->left) && same_tree(p->right, q->right);
    }else{
        return false;
    }
}

Python Code:

# func: to check if two input trees are the same
# @param p: root node of tree 1
# @param q: root node of tree 2
# @return: True or False
def same_tree(p, q):
    if not p:
        return q is None
    if not q:
        return p is None

    if p.val == q.val:
        return same_tree(p.left, q.left) and same_tree(p.right, q.right)
    else:
        return False

No comments:

Post a Comment