Skip to content

Instantly share code, notes, and snippets.

@ineersa
Created January 9, 2015 08:17
Show Gist options
  • Save ineersa/a82dc195c18087e19047 to your computer and use it in GitHub Desktop.
Save ineersa/a82dc195c18087e19047 to your computer and use it in GitHub Desktop.
<?php
class Node
{
public $data;
public $left;
public $right;
public $nextRight;
}
function newNode($data)
{
$p=new Node;
$p->data=$data;
$p->left=null;
$p->right=null;
$p->nextRight=null;
}
function connect( &$p )
{
$p->nextRight=null;
recursion ( $p );
}
function recursion ( &$p )
{
// Base case
if (!$p)
return;
// Set the nextRight pointer for p's left child
if ($p->left)
$p->left->nextRight = $p->right;
// Set the nextRight pointer for p's right child
// p->nextRight will be NULL if p is the right most child at its level
if ($p->right)
$p->right->nextRight = ($p->nextRight)? $p->nextRight->left: NULL;
// Set nextRight for other nodes in pre order fashion
recursion ($p->left);
recursion ($p->right);
}
$root= new Node;
$root->data=10;
$root->left=newNode(8);
$root->right=newNode(2);
$root->left->left=newNode(3);
connect($root);
var_dump($root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment