Created
August 20, 2016 10:08
-
-
Save antoniopicone/58a95c41562a4a9587702ef3be6932e8 to your computer and use it in GitHub Desktop.
Solution to a problem to check if a binary tree is balanced
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 | |
// check if a binary tree is balanced (it means | max-depth - min-depth | <= 1) as an AVL tree | |
// time complexity is O(N) , where N is the number of nodes | |
// space complexity iis O(h) , where h is the number of levels | |
class Node { | |
public $data; | |
public $left; | |
public $right; | |
public function __construct($data) | |
{ | |
$this->data = $data; | |
$this->left = $this->right = NULL; | |
} | |
public function getData() { | |
return $this->data; | |
} | |
} | |
class BinaryTree { | |
private $root; | |
private $nodes; | |
public function __construct($droot,$adiacence_list) | |
{ | |
$this->nodes = array(); | |
$this->root = NULL; | |
foreach($adiacence_list as $root => $leafs) { | |
if(!isset($this->nodes[$leafs[0]])) { | |
$left = new Node($leafs[0]); | |
$this->nodes[$leafs[0]] = $left; | |
} | |
if(!isset($this->nodes[$leafs[1]])) { | |
$right = new Node($leafs[1]); | |
$this->nodes[$leafs[1]] = $right; | |
} | |
$node = new Node($root); | |
$node->left = &$this->nodes[$leafs[0]]; | |
$node->right = &$this->nodes[$leafs[1]]; | |
$this->nodes[$root] = $node; | |
} | |
$this->root = &$this->nodes[$droot]; | |
} | |
public function listNodes() { | |
var_dump($this->root); | |
} | |
public function maxDepth($root) { | |
if($root == NULL) { | |
return 0; | |
} | |
return 1 + max($this->maxDepth($root->left), $this->maxDepth($root->right)); | |
} | |
public function minDepth($root) { | |
if($root == NULL) { | |
return 0; | |
} | |
return 1 + min($this->minDepth($root->left), $this->minDepth($root->right)); | |
} | |
public function isBalanced() { | |
return $this->maxDepth($this->root) - $this->minDepth($this->root) <= 1; | |
} | |
} | |
$ad_list = array( | |
'a' => array('b','c'), | |
'b' => array('d','e'), | |
'd' => array('g') | |
); | |
$bt = new BinaryTree('a',$ad_list); | |
$bt->listNodes(); | |
echo $bt->isBalanced(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment