I've been asked to draw a binary search tree that both the in order and post order traversal process the nodes in the order "ATTA". I have tried many different way but it ends up only working for one of the traversal methods.
I do believe you're just talking about a regular binary tree, because creating such a binary search tree is impossible.
Given that the post-order ends with A, we know the root must be A.
Given that we only have 2 A's in the in-order, and the root is A, we know either the left or right subtrees of the root are empty.
Given that the second last node in the post-order is a T, we know the root's child must be a T.
From here we can just check the remaining 4 possibilities:
A A A A
/ / \ \
T T T T
/ \ / \ / \ / \
A T T A A T T A
Inorder ATTA TTAA ATAT ATTA
Postorder ATTA TATA ATTA TATA
So the only possibility is:
A
/
T
/ \
A T
... and this is not a binary search tree.
Related
I'm trying to define an algorithm that returns the number of leaves at the lowest level of a complete binary tree. By a complete binary tree, I mean a binary tree whose every level, except possibly the last, is filled, and all nodes in the last level are as far left as possible.
For example, if I had the following complete binary tree,
_ 7_
/ \
4 9
/ \ / \
2 6 8 10
/ \ /
1 3 5
the algorithm would return '3' since there are three leaves at the lowest level of the tree.
I've been able to find numerous solutions for finding the count of all the leaves in regular or balanced binary trees, but so far I haven't had any luck with the particular case of finding the count of the leaves at the lowest level of a complete binary tree. Any help would be appreciated.
Do a breadth-first search, so you can aswell find a number of nodes on each level.
Some pseudo code
q <- new queue of (node, level) data
add (root, 0) in q
nodesPerLevel <- new vector of integers
while q is not empty:
(currentNode, currentLevel) <- take from top of q
nodesPerLevel[currentLevel] += 1
for each child in currentNode's children:
add (child, currentLevel + 1) in q
return last value of nodesPerLevel
Given a binary arithmetic expression tree consisting of only addition and subtraction operators, and numbers, how to balance the tree as much as possible? The task is to balance the tree without evaluating the expression, that is the number of nodes should stay the same.
Example:
+ +
/ \ / \
+ 15 >>>>>> - +
/ \ / \ / \
5 - 6 4 5 15
/ \
6 4
Addition is commutative and associative and that allows for balancing. Commutativity allows for swapping of children of consecutive '+' nodes. Associativity allows for rotations. In the above example, the transformation performed can be viewed as
Rotation right on '+' at the root.
Swapping of '5' and '-' nodes.
I was thinking of doing an in order traversal and first balancing any sub-trees. I would try to balance any sub-tree with two consecutive '+' nodes by trying all possible arrangements of nodes (there are only 12 of them) to hopefully decrease the total height of the tree. This method should reduce the height of the tree by at most 1 at any step. However, I cannot determine whether it will always give a tree of minimum height, especially when there are more than 2 consecutive '+' nodes.
Another approach could be to read the expression tree into an array and substitute any '-' subtree with a variable. And then us DP to determine the best places for brackets. This must be done bottom up, so that any '-' subtree is already balanced when it is considered by DP algorithm. However, I am worried because there could be (n+1)! ways to arrange nodes and brackets. While I am looking for an O(n) algorithm.
Is it a known problem and is there a specific approach to it?
At the risk of doing something vaguely like "evaluating" (although it isn't in my opinion), I'd do the following:
Change the entire tree to addition nodes, by propagating negation markers down to the roots. A simple way to do this would be to add a "colour" to every leaf node. The colour of a node can be computed directly during a tree walk. During the walk, you keep track of the number (or the parity, since that's the only part we're interested in) of right-hand links from a - nodes taken; when a leaf is reached, it is coloured green if the parity is even and red if the parity is odd. (Red leaves are negated.) During the walk, - nodes are changed to +.
+ +
/ \ / \
+ 15 >>>>>> + 15
/ \ / \
5 - 5 +
/ \ / \
6 4 6 -4
Now minimise the depth of the tree by constructing a minimum depth binary tree over top of the leaves, taking the leaves in order without regard to the previous tree structure:
+ +
/ \ / \
+ 15 >>>>>> + +
/ \ / \ / \
5 + 5 6 -4 15
/ \
6 -4
Turn the colours back into - nodes. The easy transforms are nodes with no red children (just remove the colour) and nodes with exactly one red child and one green child. These latter nodes are turned into - nodes; if the red child is on the left, then the children are also reversed.
The tricky case is nodes all of whose children are red. In that case, move up the tree until you find a parent which has some green descendant. The node you find must have two children (since otherwise its only child would have to have a green descendant), of which exactly one child has green descendants. Then, change that node to -, reverse its children if the right-hand child has a green descendant, and recolour green all the children of the (possibly new) right-hand child.
+ +
/ \ / \
+ + >>>>>> + -
/ \ / \ / \ / \
5 6 -4 15 5 6 15 4
Perhaps it's worth pointing out that the root node has a green descendant on the left-hand side because the very first leaf node is green. That's sufficient to demonstrate that the above algorithm covers all cases.
Is such a binary tree possible? I've drawn out what I believe to be all possible iterations, and I cannot find a tree that satisfies these properties. Note that this is not a BST, so the values of the keys don't matter. There are countless with exactly 1 "single child" node, such as :
a
/ \
b c
/ //b is only such node
d
/ \
e f
And many with exactly 3 "single child" nodes:
a
/
b
/ //a, b, and d
c
/ \
d e
/
f
Does such a binary tree exist (6 nodes, exactly 2 nodes with exactly 1 child)? If so, please provide an example.
This is an impossible structure to create with the standard binary tree containing 2 child pointers. If you had an nontraditional tree with 3 child pointers this would be possible.
I have the following implementation of a Depth First Search algorithm:
public static void printDFS(Node root) {
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while(!stack.isEmpty()) {
Node curr = stack.pop();
System.out.println(curr.getValue()) ;
if (curr.getLeft() != null) {
stack.push(curr.getLeft());
}
if (curr.getRight() != null) {
stack.push(curr.getRight());
}
}
}
and when I run it on a tree that looks like this:
0
/ \
6 7
/ \ / \
5 4 3 2
I get the visited output as: 0 -> 7 -> 2 -> 3 -> 6 -> 4 -> 5
Is this a 'correct' DFS ordering? I would have expected the output to have been a pre-order traversal (ie 0 ->6 -> 5 -> 4 -> 7 -> 3 -> 2) and I know I can get this by first pushing the right node of each subtree. But what I want to know is what is the correct visitation order in a DFS algorithm?
As already mentioned in another answer the reason why your visitation -> traversal order is "inversed" lies in the fact that you are using a Stack to keep track of the "current node".
Let me walk you through your example tree:
0
/ \
6 7
/ \ / \
5 4 3 2
stack.push(root) leads to following stack state:
0: 0 <-- (root) and Top of stack
You're popping the stack and put it in curr. In traversal terms you are now in this state:
0 <--
/ \
6 7
/ \ / \
5 4 3 2
you then proceed to add curr.getLeft() to the stack and then curr.getRight(). This leads to following stack state:
1: 7 <--(curr.getRight()) <-- Top of stack
0: 6 <--(curr.getLeft())
Repeating the same step we get following traversal state:
0
/ \
6 7<--
/ \ / \
5 4 3 2
and after adding the nodes:
2: 2 <-- Top of stack
1: 3
0: 6 <-- (initial getLeft())
as both nodes have no children, popping them from the stack and outputting them gets us to following traversal state:
0
/ \
-->6 7
/ \ / \
5 4 3 2
The rest of this is history ;)
As you specificially asked about a "correct" way (or ordering) for a DFS: There is none. You define what side you traverse to depth first.
It's a stack. What you push last will pop first
There is no such "correct DFS ordering". The main idea of DFS is to go deep; visiting children before siblings for any given node. Once you go far deep in the graph and you encounter a leaf, you backtrack and examine the nearest sibling in the same way.
The way you choose which child to examine first result in different traversing orders (or trees). Needless to say, all traversing methods result in a spanning tree over the graph. Pre-order traversing, the one you are comparing with, is probably the most well known order for DFS (or at least this is what I have seen). Others are valid but not too popular.
Here is a pseudo code for DFS:
'''
This is much more of a traversal algorithm than search.
'''
Algorithm DFS(Tree):
initialize stack to contain Tree.root()
while stack is not empty:
p = stack.pop()
perform 'action' for p
for each child 'c' in Tree.children(p):
stack.push(c)
This will search through all the nodes of tree whether binary or not.
To implement search and return.. modify the algorithm accordingly.
There are a few options to consider for your DFS algorithm:
Firstly, use Backtracking algorithm to do a DFS search.
If using Backtracking add only leftChild while traversing downwards. Otherwise reverse the order in which you push() node's children onto the Stack i.e rightChild right and then leftChild.
Again if using Backtracking, avoid cycles by creating a variable nodeVistited which will be set to true once a node has been pushed on stack. Not needed otherwise.
Try with these changes or let me know I will post code for DFS.
I am studying data structures and algorithms and this thing is really confusing me
Height of a binary tree, as it is also used in AVL search tree.
According to the book I am following "DATA STRUCTURES by Lipschutz" , it says "the depth (or height) of a tree T is the maximum number of nodes in a branch of T. This turns out to be 1 more than the largest level number of T. The tree 7 in figure 7.1 has depth 5."
figure 7.1 :
A
/ \
/ \
/ \
/ \
B C
/ \ / \
D E G H
/ / \
F J K
/
L
But, on several other resources, height has been calculated differently, though same definition is given. For example as I was reading from internet http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture5.html
" Here is a sample binary tree:
1
/ \
/ \
/ \
/ \
2 3
/ \ / \
/ \ / \
/ \ / \
6 7 4 5
/ \ / /
9 10 11 8
The height of a tree is the maximum of the depths of all the nodes. So the tree above is of height 3. "
Another source http://www.comp.dit.ie/rlawlor/Alg_DS/searching/3.%20%20Binary%20Search%20Tree%20-%20Height.pdf
says, "Height of a Binary Tree
For a tree with just one node, the root node, the height is defined to be 0, if there are 2
levels of nodes the height is 1 and so on. A null tree (no nodes except the null node)
is defined to have a height of –1. "
Now these last 2 explanations comply with each other but not with the example given in the book.
Another source says "There are two conventions to define height of Binary Tree
1) Number of nodes on longest path from root to the deepest node.
2) Number of edges on longest path from root to the deepest node.
In this post, the first convention is followed. For example, height of the below tree is 3.
1
/ \
2 3
/ \
4 5
"
In this, I want to ask how can the number of nodes and edges between root and leaf be the same ?
And what will be the height of a leaf node, according to the book it should be 1 (as the number of largest level is 0, so height should be 0+1=1,
but it is usually said height of leaf node is 0.
Also why does the book mention depth and height as the same thing?
This thing is really really confusing me, I have tried clarifying from a number of sources but cant seem to choose between the two interpretations.
Please help.
==> I would like to add to it since now I am accepting the conventions of the book,
in the topic of AVL search trees where we need to calculate the BALANCE FACTOR (which is the difference of the heights left and right subtrees)
it says :
C (-1)
/ \
(0) A G (1)
/
D (0)
The numbers in the brackets are the balance factors.
Now, If I am to follow the book height of D is 1 and right subtree of G has height (-1) since its empty, so Balance factor of G should be = 1-(-1)=2!
Now why has it taken the height of D to be 0 here ?
PLEASE HELP.
The exact definition of height doesn't matter if what you care about is balance factor. Recall that balance factor is
height(left) - height(right)
so if both are one larger or one smaller than in your favorite definition of height, the balance factor doesn't change, as long as you redefine the height of an empty tree accordingly.
Now the problems is that the "maximum number of nodes in a branch" definition is both recursive but doesn't specify a base case. But since the height of a single-element tree is one according to this definition, the obvious choice for the height of a zero-element tree is zero, and if you work out the formulas you'll find this works.
You can also arrive at the zero value by observing that the base case of the other definition is -1, and otherwise it always gives a value one less than the "max. nodes in a branch" definition.