leetcode 617. Merge Two Binary Trees 二叉树合并 + 深度优先遍历DFS

清疚 2022-06-03 05:15 309阅读 0赞

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.

本题题意很简单,直接合并即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. /*
  18. struct TreeNode
  19. {
  20. int val;
  21. TreeNode *left;
  22. TreeNode *right;
  23. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  24. };
  25. */
  26. class Solution
  27. {
  28. public:
  29. TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2)
  30. {
  31. if (t1 == NULL && t2 == NULL)
  32. return NULL;
  33. else if (t1 == NULL && t2 != NULL)
  34. return t2;
  35. else if (t1 != NULL && t2 == NULL)
  36. return t1;
  37. else
  38. {
  39. TreeNode* root = new TreeNode(t1->val+t2->val);
  40. root->left = mergeTrees(t1->left,t2->left);
  41. root->right = mergeTrees(t1->right,t2->right);
  42. return root;
  43. }
  44. }
  45. };

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读