I have a list of numbers like [1, 2, 2, 3, 3, 2, 3, 3, 4]
which I need to convert into a tree, like below:
1
/ | \
2 2 2
/ \ / \
3 3 3 3
\
4
Note: within the list, each number cannot be +2 or more than +2 compared to the preceding value.
This can be done in a natural way, using a stack of nodes:
x
in the list:
node
with value x
.x - 1
.node
to the node at the top of the stack.node
to the stack.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.