Similar Problems
Similar Problems not available
Create Binary Tree From Descriptions - Leetcode Solution
Companies:
LeetCode: Create Binary Tree From Descriptions Leetcode Solution
Difficulty: Medium
Topics: hash-table depth-first-search breadth-first-search tree binary-tree array
Problem statement:
Given a string input that represents a binary tree, create a binary tree based on the input. The input is a comma-separated string where each element represents either a node or an empty tree.
For example, the input "1,2,3,null,null,4,5" represents the following binary tree:
1
/
2 3
/
4 5
Solution:
To solve this problem, we can use a recursive approach where we split the input string into two parts based on the left and right subtrees. We start by creating a node with the first element of the input string, then we recursively create the left and right subtrees based on the remaining string.
We will start by defining the Tree Node class that we will use to create the binary tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Now we can define the function that will create the binary tree based on the input string.
def createTree(s):
if not s:
return None
values = s.split(",")
root = TreeNode(int(values[0]))
if len(values) == 1:
return root
left_s = values[1]
right_s = "" if len(values) < 3 else values[2]
root.left = createTree(left_s)
root.right = createTree(right_s)
return root
We start by checking if the input string is empty, in which case we return None. Then we split the input string into its values. We create the root node with the first value, and if there is only one value in the input string, we return the root node.
If there are two or more values in the input string, we extract the left and right subtree strings. If there is no right subtree, the right_s string will be empty.
We then recursively create the left and right subtrees using the left_s and right_s strings, respectively. Finally, we return the root node of the created binary tree.
We can test our function with the given example input string "1,2,3,null,null,4,5".
s = "1,2,3,null,null,4,5"
root = createTree(s)
We can then traverse the tree using any traversal algorithm to verify that the binary tree is correctly created.
For example, using inorder traversal, we get the following output.
def inorderTraversal(root):
if not root:
return []
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
inorderTraversal(root) # Output: [2, 1, 4, 3, 5]
This confirms that the binary tree is correctly created from the given input string.
Create Binary Tree From Descriptions Solution Code
1