preorder binary tree traversal fails - algorithm

I am having trouble with the equivalent binary trees exercise on the go tour.
I've written a Walker() function to traverse the tree in node-left-right order, then used the Same() function to test two identical binary trees for equivalence.
Here is a link to my code: https://go.dev/play/p/vakNgx_CD3L
See comments in the linked go code. For some reason, with this traversal order, the equivalence tests fails when it should work. Switching the order to left-node-right or right-node-left works, though.
The print output also confuses me. This is the result when run. Why don't the first 10 numbers from traversing tree 1 match the second set of 10 numbers from traversing tree 2?
10
5
3
1
2
4
7
6
9
8
7
4
2
1
3
5
6
9
8
10
false
false

I think the problem here is, you are using the https://pkg.go.dev/golang.org/x/tour/tree#New function which returns a random binary tree from 1k to 10k values.
The "Random" word is of importance here, so you can not expect to get same binary tree as a output from a call to tree.New(1) function.
Though the tree nodes will have values from 1 to 10 (incase of k=1) the order of the tree returned will be diffrent. You can see this clearly if you print the tree with the .String() function.
Take a look at below playground code where I have printed the tree which clearly shows the returned tree will be different at each call to the tree.New function.
https://go.dev/play/p/WkF8frfno17
I hope this helps :).

Related

Given a list of keys, how do we find the almost complete binary search tree of that list?

I saw an answer here with the idea implemented in Python (not very familiar with Python) - I was looking for a more general algorithm.
EDIT:
For clarification:
Say we are given a list of integer keys: 23 44 88 12 74 32 7 39 10
That list was chosen arbitrarily. We are to create an almost complete (or complete) binary search tree from that list. There is supposed to be only one such tree...how do we find it?
A binary search tree is constructed so that all items on a node's left subtree are less than the node, and all nodes on the right subtree are greater than the node.
A complete (or almost complete) binary tree is one in which all levels except possibly the last are completely full, and the bottom level is filled to the left.
So, for example, this is an almost-complete binary search tree:
4
/ \
2 5
/ \
1 3
This is not:
3
/ \
2 4
/ \
1 5
Because the bottom level of the tree is not filled from the left.
If the number of items is one less than a power of two (i.e. 3, 7, 15, etc.), then building the tree is easy. Start by sorting the list. Then, take the middle element as the root. So if you have [1,2,3,4,5,6,7], and the root node is 4.
You do the same thing recursively for the right and left halves of the array.
If the number of items is not one less than a power of two, you have to adjust the starting point (the root node) so that the bottom row is left-filled. Note that you might have to apply that adjustment recursively, as well, whenever your subtree length is not one less than a power of two.
Since this is a homework assignment, I'll leave that for you to figure out.

3-element binary search trees

I'm working through a past exam paper for my advanced programming course and I've gotten stuck at this question
What property must the values in a binary search tree satisfy? How many different binary search trees are there containing the three values 1 2 3? Explain your answer.
I can answer the first part easily enough but the second bit, about the number of possible trees has me stumped. My first instinct is to say that there is only a single tree possible, with 2 as the root because the definition says so, but this question is work 8 marks out of a total of 100 for the entire paper, so I can only assume that it's a trick question, and there's a more subtle explanation, but there's nothing in the lecture notes that explains this. Does anyone know who to answer this question?
The question doesn't say that the tree is balanced, so think about whether 1 or 3 can be at the root node.
Try to think about all possible binary trees with these three nodes. How many of those trees fulfill the property of binary search tree?
I think that a trick is that a tree can be a degenerate one (effectively, a linked list of elements):
1
\
2
\
3
And variations thereof.
Also, are these trees considered to be identical ?
2 2
/ \ / \
3 1 1 3
If I remember correctly, the root of the tree does not have to be the "middle element". Thus there are a few more combinations of trees:
2
1 3
or
1
2
3
or
1
3
2
or
3
2
1
or
3
1
2
Maybe I forget a few, but I think you'll get the idea. Just for my notation: Newline meets get down in the tree, right and left of the upperline showes whether it is right or left of its parent node ;)

When two trees are equal?

If in-order traversal of two binrary trees (not binary search trees) are the same, does it guarantee that the two trees are the same?
if answer is no, then what about both in-order and pre-order traversal are the same?
Definitely not. The two trees
b
/ \
a d
/ \
c e
and
d
/ \
b e
/ \
a c
both have an inorder traversal of a b c d e. They are, in fact, rotations, an operation which preserves inorder traversal.
NO, and its seen with this simple example
3 2
2 1 3
1 0
0
Both have same inorder traversals [0,1,2,3]
But if inorder and preorder traversals are same then the trees are equal.
I'm thinking "no."
It's possible for two trees to be balanced differently, but have the same "order" of node values. For instance, if, of the set
1,2,3,4,5,6,7
You build a tree:
4
2 6
1 3 5 7
in-order traversal will yield 1,2,3,4,5,6,7.
however, if you choose a different root node (if the list is not sorted correctly beforehand)
5
4 6
2 7
1 3
These two trees will give the same in-order traversal result, but are (clearly) not identical.
or even
7
6
5
4
3
2
1
et cetera.
This is also related to a problem with BSP (binary space partition) trees, typically used in game development collision detection and visibility determination.
The BSP stores triangles in a tree. Each node contains a triangle or facet. The left node contains all children that are "behind" the facet, while the right child contains everything that is in "front." Recurse as expected.
If you pick the left-most facet in the scene as your root, the right child will then own every other facet. If you make a bad decision for the right child, the same thing will happen. It's perfectly possible for one to build a BSP compiler that, through idiotic analysis, builds a "tree" that is actually a list (as in my last example above). The problem is to partition the data set so that each node divides the remaining list as equally as possible. This is one of the reasons that BSPs are typically generated at compile time, as building one for a very complex geometry can take hours to find the/an optimal solution.
Inorder and any one of pre-order or post-order, uniquely define a tree structure. Nothing less.
One thing you can do is use level order
5
4 6
2 7
1 3
lvel order- 5 4 6 2 N N 7 1 3 N N N N N N

What is the name of a data structure looking like bowling pins?

First of all, sorry for the title. Someone please propose a better one, I really didn't know how to express my question properly.
Basically, I'm just looking for the name of a data structure where the elements look like this (ignore the dots):
......5
....3...2
..4...1...6
9...2...3...1
I first thought it could be a certain kind of "tree", but, as wikipedia says:
A tree is [...] an acyclic connected graph where each node has zero or more children nodes and at most one parent node
Since there can be more than one parent by node in the data structure I'm looking for, it's probably not a tree.
So, here's my question:
What is the name of a data structure that can represent data with the following links between the elements? (/ and \ being the links, again, ignore the dots):
......5
...../..\
....3...2
.../..\./..\
..4...1...6
../.\./..\./..\
9...2...3...1
I think it isn't totally wrong to call it a Tree, although "Digraph" (directed graph) would be a more proper term.
First of all, sorry for the title.
Someone please propose a better one, I
really didn't know how to express my
question properly.
The title is fine, I LOL'd hard when I opened the question. I am going to start calling them "Bowling Pins" now :)
5
3 2
4 1 6
9 2 3 1
The most popular thing I reckon, which was laid out like this, is Pascal's triangle. It's the structure used to calculate binomial coefficients; each node is the sum of its parents:
http://info.ee.surrey.ac.uk/Personal/L.Wood/publications/MSc-thesis/fig36.gif.
Usuallly, when it comes to implementing such algorithms (such class is commonly referred to as "dynamic programming"), this "structure" is usually represented as a simple two-dimensional array. See here, for example:
n\k 0 1 2 3 4
------------------
0 1 0 0 0 0
1 1 1 0 0 0
2 1 2 1 0 0
3 1 3 3 1 0
4 1 4 6 4 1
5 1 5 10 10 5
6 1 6 15 20 15
I think, that there's no formal name for such a structure, but in dynamic programming such stuff is just... arrays.
But from now on, as NullUserException suggests I'm totally calling it "bowling pins" :-)
A "dag", or directed acyclic graph, is a graph with directed edge in which there may be multiple paths to a node, and some nodes may have both incoming and outgoing edges, but there is no way to leave any node and return to it (there are no cycles). Note that in a finite DAG at least one node must have nothing but outgoing edges and at least one must have nothing but incoming edges. Were that not the case, it would be possible to move continuously through the graph without ever reaching a dead end (since every node would have an exit), and without visiting any node twice (since the graph is acyclic). If there are only a finite number of nodes, that's obviously impossible.
Since there can be more than one parent by node in the data structure I'm looking for, it's probably not a tree.
What you're looking for is probably a graph. A tree is a special case of a graph where each node has exactly one parent. (except the root which has none)

Binary search on unsorted arrays?

I came across this document Binary Search Revisited where the authors have proved/explained that binary search can be used for unsorted arrays (lists) as well. I haven't grokked much of the document on a first reading.
Have any of you already explored this ?
I've just read the paper. To me the author uses the term binary search to address the Bisection method used to find the zeros of a continuous function.
The examples in the paper are clearly inspired to problems like find the zero into an
interval (with translation on the y axe) or find the max/min of a function in tabular data.
The arrays the essay consider are not random filled ones, you will find a rule to construct them (it is the rule tied to the function used to dump them)
Said that it is a good chance of tinkering about different algorithms belonging to a common family in order to find similarity and differences. A good chance to expand your experiences.
Definitely not a new concept or an undervalued one.
Lookin for 3 into that unsorted list with binary or bisection :
L = 1 5 2 9 38 11 3
1-Take mid point in the whole list L : 9
3 < 9 so delete the right part of the list (38 11 3)
here you can already understand you will never find 3
2-Take mid point in the remaining list 1 5 2 : 5
3 > 5 so delete the right part of the list (5 2)
remains 1
Result : 3 unfound
Two remarks:
1-the binary or bisection algorithm consider right and left as an indication of the order
So i have rudely applied the usual algo considering right is high and left is low
If you consieder the opposit, ie right is low and left is high, then, trying to find 3 in this slighty similar list will lead to " 3 unfound"
L' = L = 1 5 2 9 3 38 11
3 < 9 / take right part : 3 38 11
mid point 38
3 < 38 take right part : 11
3 unfound
2- if you accept to re apply systematicly the algorithm on the dropped part of the list than it leads to searching the element in a list of n elements Complexity will be O(n) exactly the same as running all the list from beg to end to search your value.
The time of search could be slightly shorter.
Why ? let's consider you look one by one from beg. to end for the value 100000 in a sorted list. You will find it at the end of your list ! :-)
If now this list is unorderd and your value 100000 is for example exactly at the mid point ... bingo !!
Binary Search can be implemented on a rotated unsorted array/list.

Resources