目录
参考了官方题解的深度优先搜索(递归)
方法: 深度优先搜索(递归)
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
/**
* @param TreeNode $root1
* @param TreeNode $root2
* @return TreeNode
*/
function mergeTrees($root1, $root2) {
if ($root1 == null) return $root2;
if ($root2 == null) return $root1;
$merged = new TreeNode($root1->val + $root2->val);
$merged->left = self::mergeTrees($root1->left, $root2->left);
$merged->right = self::mergeTrees($root1->right, $root2->right);
return $merged;
}
}
解释: null
测试结果:
执行用时:16 ms, 在所有 PHP 提交中击败了95.08%的用户
内存消耗:15.8 MB, 在所有 PHP 提交中击败了100.00%的用户
通过测试用例:182 / 182