源题目

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

617. 合并二叉树

难度简单751
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
image.png

输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7
注意: 合并必须从两个树的根节点开始。

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($val = 0, $left = null, $right = null) {
  8. * $this->val = $val;
  9. * $this->left = $left;
  10. * $this->right = $right;
  11. * }
  12. * }
  13. */
  14. class Solution {
  15. /**
  16. * @param TreeNode $root1
  17. * @param TreeNode $root2
  18. * @return TreeNode
  19. */
  20. function mergeTrees($root1, $root2) {
  21. if(!$root1 && !$root2) return null;
  22. if(!$root2) return $root1;
  23. if(!$root1) return $root2;
  24. $root1->left = $this->mergeTrees($root1->left,$root2->left);//左边树处理
  25. $root1->right = $this->mergeTrees($root1->right,$root2->right);//右边树处理
  26. $root1->val += $root2->val;//重合数据相加
  27. return $root1;
  28. }
  29. }