chandan374
Build binary tree from level order array
I am new to elixer, I need some help to construct binary tree from list of element(given in level order). Due to immutability i’m facing difficutly to implement this.
For ex: [1, 2, 3, -1, -1, -1, -1] will be represented as:
1
/ \
2 3
Here -1 means, node will be null.
Expected Output Format:
TreeNode{
data: 1,
left: TreeNode{
data: 2,
left: nil,
right: nil
},
right: TreeNode{
data: 3,
left: nil,
right: nil
}
}
In ruby, we can implement in this way.
def input_tree(input)
val = input[0]
input.shift()
root = TreeNode.new(val)
queue = []
queue.push(root)
while queue.size > 0
current_node = queue[0]
queue.shift()
leftValue = input[0]
input.shift()
rightValue = input[0]
input.shift()
if leftValue != -1
leftNode = TreeNode.new(leftValue)
current_node.left = leftNode
queue.push(leftNode)
end
if rightValue != -1
rightNode = TreeNode.new(rightValue)
current_node.right = rightNode
queue.push(rightNode)
end
end
return root
end
TIA ![]()
Marked As Solved
al2o3cr
Here’s an approach that uses a pair of recursive functions:
defmodule TreeNode do
defstruct ~w[data left right]a
end
defmodule TreeBuild do
@nothing -1
def run([root | rest]) do
[[left, right]] = subnodes(1, rest)
%TreeNode{data: root, left: left, right: right}
end
def subnodes(0, []), do: []
def subnodes(count, input) do
{roots, rest} = Enum.split(input, 2*count)
next_count = Enum.count(roots, & &1 != @nothing)
child_nodes = subnodes(next_count, rest)
roots
|> build_nodes(child_nodes, [])
|> Enum.chunk_every(2, 2, [nil])
end
def build_nodes([], _, acc), do: Enum.reverse(acc)
def build_nodes([@nothing | roots], child_nodes, acc) do
build_nodes(roots, child_nodes, [nil | acc])
end
def build_nodes([root | roots], [], acc) do
node = %TreeNode{data: root, left: nil, right: nil}
build_nodes(roots, [], [node | acc])
end
def build_nodes([root | roots], [[left, right] | child_nodes], acc) do
node = %TreeNode{data: root, left: left, right: right}
build_nodes(roots, child_nodes, [node | acc])
end
end
TreeBuild.run([1, 2, 3, -1, -1, -1, -1])
TreeBuild.run([5,4,8,11,-1,17,4,7,-1,-1,-1,5, -1, -1, -1, -1])
Some notes on the implementation:
- the sample input has one fewer -1 on the end than I expected at first; this version of
build_nodesis tolerant of any number of trailing -1s. chunk_everyis used to tidily handle cases wherebuild_nodesreturns an odd number of nodes by providing anilforleftovers
@Eiji I believe the error in your diagram is the two -1s under the -1 that’s a right-child of 4. -1s on a given level shouldn’t consume any input values in the next level.
3
Also Liked
Eiji
(…) if a node has an index
i, its children are found at indices2i+1(for the left child) and2i+2(for the right) (…)
With above writing code is really simple:
defmodule TreeNode do
defstruct ~w[data left right]a
end
defmodule Example do
def sample(input, index \\ 0) do
data = Enum.at(input, index)
unless data in [nil, -1] do
%TreeNode{
data: data,
left: sample(input, index * 2 + 1),
right: sample(input, index * 2 + 2)
}
end
end
end
iex> Example.sample([1, 2, 3, -1, -1, -1, -1])
%TreeNode{
data: 1,
left: %TreeNode{data: 2, left: nil, right: nil},
right: %TreeNode{data: 3, left: nil, right: nil}
}
3
cevado
Popular in Questions
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Hello, I get Persian date from my client and convert it to normal calendar like this:
def jalali_string_to_miladi_english_number(persi...
New
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Using vs code and installed ElixirLS: support and debugger.
And I got an error popped up on start up says
Failed to run ‘elixir’ comma...
New
Hey,
Just curious what are the main benefits of Elixir compared to Clojure?
When is Elixir more useful than Clojure and vice versa?
Th...
New
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Hi!
In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir?
Searched the docs for ip address and the web, no good results.
Thanks!
New
I would like to know what is the best IDE for elixir development?
New
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)?
Would
mix ecto.rollback -v 200809061...
New
Other popular topics
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!)
This post collects co...
New
I have an umbrella app.
Some of the apps inside depend on other apps in the umbrella, unsurprisingly.
I’m writing a test for one of the...
New
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including.
What is Phoenix LiveV...
New
After calling mix ecto.create I get this error:
17:00:32.162 [error] GenServer #PID<0.412.0> terminating
** (Postgrex.Error) FATAL...
New
Hello everybody,
usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum.
...
New
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine)
This is a plugin that adds support for Elixir to JetBrains IntelliJ...
New
What is the proper way to load a module from a file in to IEX?
In the python world, doing something like this pretty standard:
from ....
New
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









