如果给定的树可以是任意的二叉树呢?你之前的给出的算法还有效吗?
注意:你只能使用常量的额外内存空间
例如:
给出的二叉树如下: 1↵ / ↵ 2 3↵ / ↵ 4 5 7
调用完你给出的函数之后,这棵树应该变成:
1 -> NULL↵ / ↵ 2 -> 3 -> NULL↵ / ↵ 4-> 5 -> 7 -> NULL
<?php
class TreeLinkNode {
public $left = null;
public $right = null;
public $next = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function connect($root) {
if ($root->left != null && $root->right != null) {
$root->left->next = $root->right;
}
if ($root->next != null) {
if ($root->next->left != null) {
if ($root->right != null) {
$root->right->next = $root->next->left;
} elseif ($root->left != null) {
$root->left->next = $root->next->left;
}
}
if ($root->next->right != null) {
if ($root->right != null) {
$root->right->next = $root->next->right;
} elseif ($root->left != null) {
$root->left->next = $root->next->right;
}
}
}
if ($root->left != null) {
connect($root->left);
}
if ($root->right != null) {
connect($root->right);
}
return $root;
}
$node1 = new TreeLinkNode(1);
$node2 = new TreeLinkNode(2);
$node3 = new TreeLinkNode(3);
$node4 = new TreeLinkNode(4);
$node5 = new TreeLinkNode(5);
$node6 = new TreeLinkNode(6);
$node7 = new TreeLinkNode(7);
$node1->left = $node2;
$node1->right = $node3;
$node2->left = $node4;
$node2->right = $node5;
//$node3->left = $node6;
$node3->right = $node7;
$root = connect($node1);
output($root);
function output($root) {
if ($root != null) {
print $root->val.'->'.$root->next->val.';';
}
if ($root->left != null) {
output($root->left);
}
if ($root->right != null) {
output($root->right);
}
}