【二叉树】合并二叉树

题目链接:https://leetcode.com/problems/merge-two-binary-trees/#/description

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    //  存储t1,t2合并之后的结果
    TreeNode* t3 = new TreeNode(NULL);
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        t3 = merge(t1,t2,0);
        return t3;
    }
    //  t1,t2同时合并
    TreeNode* merge(TreeNode* t1,TreeNode* t2,int level){
        TreeNode* node = new TreeNode(NULL);
        if(t1==NULL&&t2==NULL){
            return NULL;
        }else{
            if(t1==NULL){
                return t2;
            }else if(t2==NULL){
                return t1;
            }else{
                //  值合并
                node->val=t1->val+t2->val;
                level++;
                node->left=merge(t1->left,t2->left,level);
                node->right=merge(t1->right,t2->right,level);
            }
        }
        return node;
    }
};


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页