Created
January 9, 2015 08:17
-
-
Save ineersa/a82dc195c18087e19047 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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