617. Merge Two Binary Trees(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/80161245

https://leetcode.com/problems/merge-two-binary-trees/description/

题目:合并2棵二叉树

思路:采用后序遍历的方法,分为3种情况:

1 如果t1非空并且t2非空,则t1加上t2的值,返回t1,否则直接返回t1
2 t1为空且t2非空,返回t2
3 t1和t2都为空,返回NULL

代码:

class Solution {
public:
    TreeNode *dfs(TreeNode* t1,TreeNode* t2){
              if(!t1&&!t2) return NULL;

              TreeNode *left  = dfs((t1?t1->left:NULL),(t2?t2->left:NULL));
              TreeNode *right = dfs((t1?t1->right:NULL),(t2?t2->right:NULL));

              if(t1){
                 t1->val+=(t2?t2->val:0);
                 t1->left = left;
                 t1->right = right;
              }

             else
                 return t2;

             return t1;
    }
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
              t1 = dfs(t1,t2);
              return t1;
    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/80161245
今日推荐