/**
* 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 $root
* @return NULL
*/
function flatten($root)
{
return $this->flattenAndReturn($root);
}
public function flattenAndReturn(&$root)
{
if (empty($root)) {
return null;
}
$leftLast = $this->flattenAndReturn($root->left);
$rightLast = $this->flattenAndReturn($root->right);
if (!empty($leftLast)) {
$leftLast->right = $root->right;
$root->right = $root->left;
$root->left = null;
}
return $rightLast ? $rightLast : ($leftLast ? $leftLast : $root);
}
}
|