二叉树合并

算法期中考遇到一道合并二叉树的题目的题目,感觉对理解二叉树的归并和二叉树本身这个的数据结构都挺有帮助,因此记录下来:

题目:

 

 代码:

class Solution {
public:
  void helper(TreeNode **res, TreeNode* T1, TreeNode* T2) {
        if (T1 != NULL || T2 != NULL) {         
            if (T1 != NULL && T2 != NULL) {
                *res = new TreeNode(T1->val + T2->val);
                helper(&(*res)->left, T1->left, T2->left);
                helper(&(*res)->right, T1->right, T2->right);
            }
            else if (T1 != NULL && T2 == NULL) {
                *res = new TreeNode(T1->val);
                helper(&(*res)->left, T1->left, NULL);
                helper(&(*res)->right, T1->right, NULL);
            }
            else if (T1 == NULL && T2 != NULL) {
                *res = new TreeNode(T2->val);
                helper(&(*res)->left, NULL, T2->left);
                helper(&(*res)->right, NULL, T2->right);
            }
            
        }
        else {
            return;
        }
    }
    TreeNode* merge(TreeNode* T1, TreeNode* T2) {
        TreeNode *res;
        this->helper(&res, T1, T2);
        return res; 
    }
};

 

posted @ 2017-11-14 20:02  fengzw  阅读(856)  评论(0编辑  收藏  举报