2196. Create Binary Tree From Descriptions #29
-
You are given a 2D integer array
Construct the binary tree described by The test cases will be generated such that the binary tree is valid. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2196. Create Binary Tree From Descriptions <?php
// Definition for a binary tree node.
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
public function __construct($value) { $this->val = $value; }
}
function createBinaryTree($descriptions) {
$nodes = [];
$children = [];
// Create nodes and build the tree
foreach ($descriptions as $description) {
$parentVal = $description[0];
$childVal = $description[1];
$isLeft = $description[2];
if (!isset($nodes[$parentVal])) {
$nodes[$parentVal] = new TreeNode($parentVal);
}
if (!isset($nodes[$childVal])) {
$nodes[$childVal] = new TreeNode($childVal);
}
if ($isLeft) {
$nodes[$parentVal]->left = $nodes[$childVal];
} else {
$nodes[$parentVal]->right = $nodes[$childVal];
}
$children[$childVal] = true;
}
// Find the root node (node that is not a child of any other node)
foreach ($nodes as $val => $node) {
if (!isset($children[$val])) {
return $node;
}
}
return null;
}
// Example usage:
$descriptions1 = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]];
$descriptions2 = [[1,2,1],[2,3,0],[3,4,1]];
$root1 = createBinaryTree($descriptions1);
$root2 = createBinaryTree($descriptions2);
function printTree($node) {
if ($node == null) {
return null;
}
$result = [$node->val];
$result[] = printTree($node->left);
$result[] = printTree($node->right);
return $result;
}
print_r(printTree($root1)); // Output: [50, [20, [15], [17]], [80, [19]]]
print_r(printTree($root2)); // Output: [1, [2, null, [3, [4]]]]
?> This code defines a TreeNode class to represent each node in the binary tree. The createBinaryTree function constructs the tree based on the descriptions provided and finds the root node by identifying the node that is not a child of any other node. The printTree function is used to print the tree structure for verification. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2196. Create Binary Tree From Descriptions