Permalink
Browse files

adding binary tree/element types

  • Loading branch information...
1 parent a7e8b8b commit 4731be243ae66bf7db2e1b9557a78434907deb90 @enygma committed Dec 24, 2012
Showing with 159 additions and 0 deletions.
  1. +87 −0 PBinaryElement.php
  2. +72 −0 PBinaryTree.php
View
@@ -0,0 +1,87 @@
+<?php
+
+namespace Pv;
+
+class PBinaryElement extends Variable
+{
+ /**
+ * Current element's data
+ * @var mixed
+ */
+ protected $value = null;
+
+ /**
+ * Previous element
+ * @var \Pv\PBinaryElement
+ */
+ private $prev = null;
+
+ /**
+ * Next element
+ * @var \Pv\PBinaryElement
+ */
+ private $next = null;
+
+ /**
+ * Create the element based on the value
+ *
+ * @param mixed $value Value of the new element
+ * @return null
+ */
+ public function __construct($value)
+ {
+ $this->value = $value;
+ }
+
+ /**
+ * Add another value to the data set
+ *
+ * @param mixed $value Item value
+ * @return null
+ */
+ public function add($value)
+ {
+ if ($this->value < $value) {
+ if ($this->next !== null) {
+ $this->next->add($value);
+ } else {
+ $this->next = new \Pv\PBinaryElement($value);
+ }
+ } else {
+ if ($this->prev !== null) {
+ $this->prev->add($value);
+ } else {
+ $this->prev = new \Pv\PBinaryElement($value);
+ }
+ }
+ }
+
+ /**
+ * Output the contents of the current and prev/next elements
+ *
+ * @return null
+ */
+ public function dump()
+ {
+ if ($this->prev !== null) {
+ $this->prev->dump();
+ }
+
+ echo print_r($this->value, true) . "\n";
+
+ if ($this->next !== null) {
+ $this->next->dump();
+ }
+ }
+
+ public function get($find, $lvl)
+ {
+ if ($find == $lvl) {
+ return $this;
+ } else {
+ return $this->next->get($find, $lvl++);
+ }
+ }
+}
+
+?>
View
@@ -0,0 +1,72 @@
+<?php
+
+namespace Pv;
+
+class PBinaryTree extends Variable
+{
+ /**
+ * Base node of the tree
+ * @var \Pv\PBinaryElement
+ */
+ private $base = null;
+
+ /**
+ * Value of the tree (not really used)
+ * @var mixed
+ */
+ protected $value = null;
+
+ /**
+ * Create the binary tree object
+ *
+ * @param mixed $value Value of tree (assigned, but not used)
+ */
+ public function __construct($value = null)
+ {
+ $this->value = $value;
+ }
+
+ /**
+ * Add a new value to the tree
+ *
+ * @param mixed $data Data for new value
+ */
+ public function add($data)
+ {
+ if ($this->base !== null) {
+ $this->base->add($data);
+ } else {
+ $this->base = new \Pv\PBinaryElement($data);
+ }
+ }
+
+ /**
+ * Find the element with the matching value
+ *
+ * @param mixed $find Value to find
+ * @param integer $lvl Tracking for nesting level
+ * @return \Pv\PBinaryElement
+ */
+ public function get($find, $lvl = 1)
+ {
+ if ($find == $lvl) {
+ return $this->base;
+ } else {
+ return $this->base->get($find, $lvl+1);
+ }
+ }
+
+ /**
+ * Dump out the contents of the tree
+ *
+ * @return null
+ */
+ public function dump()
+ {
+ if ($this->base !== null) {
+ $this->base->dump();
+ }
+ }
+}
+
+?>

0 comments on commit 4731be2

Please sign in to comment.