《leetcode-php》把二叉树的左兄弟节点指向右兄弟节点

如果给定的树可以是任意的二叉树呢?你之前的给出的算法还有效吗?
注意:你只能使用常量的额外内存空间
例如: 
给出的二叉树如下:  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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值