You are viewing a single comment's thread. Return to all comments →
PHP sol. Thanks... Node class was not provided. Bit easier in js or python.
<?php //$_fp = fopen("php://stdin", "r"); class Node { public $data; public $left; public $right; public function __construct($data) { $this->data = $data; $this->left = null; $this->right = null; } } function preOrderRec($root) { $w = ''; if ($root !== null) { $w .= $root->data . ' '; $w .= preOrderRec($root->left); $w .= preOrderRec($root->right); } return $w; } function preOrder($root) { $out = preOrderRec($root); echo trim($out) . "\n"; } //insert values into bin search tree function insert($root, $data) { if ($root === null) { return new Node($data); } if ($data < $root->data) { $root->left = insert($root->left, $data); } else { $root->right = insert($root->right, $data); } return $root; } $lines = trim(fgets(STDIN)); $input = array_map('intval', explode(' ', trim(fgets(STDIN)))); $root = null; foreach ($input as $value) { $root = insert($root, $value); } preOrder($root); ?>
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
PHP sol. Thanks... Node class was not provided. Bit easier in js or python.