leadcode of Hot100 series --617. merge binary tree

Combined, the structure is the intersection of two portions of the tree, adding the data, otherwise, taking a non-empty portion.
So, here is the equivalent of two trees while traversing:
If two trees node is not empty, the data are added,
or directly copied pointer to the node is not empty.

Note: There is no application memory, and direct the transformation of the original tree, which saves time for memory, and save some memory.

struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2){
    
    struct TreeNode *pTemp = NULL;
    
    if ((NULL == t1) && (NULL == t2))
        return NULL;
    else if ((NULL != t1) && (NULL != t2))
    {
        pTemp = t1;
        pTemp->val = t1->val + t2->val;
    }
    else if (NULL != t1)
    {
        return t1;
    }
    else if (NULL != t2)
    {
        return t2;
    }
    pTemp->left = mergeTrees(t1->left, t2->left);
    pTemp->right = mergeTrees(t1->right, t2->right);

    return pTemp;

Guess you like

Origin www.cnblogs.com/payapa/p/11111967.html