leaf to root bst traversal - java

I was just wondering, given a node which points to its left and right children, is it possible to somehow get an inorder print of the whole bst tree?
All i know about the tree is that it is BST.
And all I know about the node is that he knows who his children are (left and right).
I don't have access to neither the root nor the father of the node.
The node chosen is picked randomly, and I need to return an inorder of the whole tree.
I think there is not enough info to get started at, and my friend got this question during a job interview, and was wondering if that was an unsolvable question or is there a trick I don't know about?
Thanks in advance for any help :)

The only thing you can do from this situation is to travel downwards, because you have no pointer to the parent node. The only case when you can print the whole tree is when the node considered is the root.
So, you can get the inorder print of the subtree rooted at the current node. If this node is the root, then it prints the whole tree. If it is not, then it does not.
Just in case, inorder print is simple:
def inorder(node):
if node == null: return
inorder(node.left)
print node.data
inorder(node.right)

Related

Remove the node in Binary Search Tree

How can I remove all isRemoved=true; data in Binary Search Tree in one method?
Or two it doesn't matter.
There is a remove method already and it marks the node that is coming from method isRemoved=true.
So,constructor has four specilization they are Type data,left,right,isRemoved.
The method can work recursively or not doesn't matter.
My idea is traversing all of the nodes when I found the removed go and delete method and delete it then turn back and keep going look at the nodes. I couldn't implement the idea because BST is complicated. Can you guys give me some clue?
First you will need to decide how you are going to traverse your tree (inorder, preorder, postorder).
Then you will handle three separate cases for a node to be deleted; when the node is a leaf, when the node has one child, and when there are both a left and a right child.
If the node is a leaf, you can remove it.
If the node has a child, you can set the node's child to be the parent node's child, then remove the node.
If the node has two children, you can go to the subtree of the left child and replace the node with the rightmost child of the left subtree. Since the rightmost node in the subtree is a leaf, you can replace without rebalancing the tree.
Traverse the tree while removing the isRemoved=true nodes using one of the methods above until you reach the last node in the traversal.

Recursion in binary tree to traverse the entire tree

I am studying binary trees. I saw online a code to traverse the entire binary tree. Here's the code I got:
'''
public void showAll(Node node)
{
Node parent = node;
if(parent != null)
{
System.out.println(" " + parent.person);
showAll(parent.leftChild);
showAll(parent.rightChild);
}
}
'''
What I dont understand is how this function can print the right child? According to code everytime the function is called left child is printed. The code never reaches the right child.
This is a textbook implementation of postorder traversal. Also known by some as "bottom up" traversal.
For each iteration the leftmost node then the rightmost node is printed. If the parent node is ever null then the tree is past the highest node, i.e. the algorithm has finished.
Try to dry run the code with binary tree having, say 5 nodes. And then you'll probably figure it out. Even then if you are facing problems, learn a little about how a compiler calls functions or what actually stacktrace is.

Time complexity of deletion in binary search tree

Assume the height of the BST is h.
If we want to delete a node with two children, then what would be the time complexity of the process.
I know that in a normal binary tree, the time complexity for deletion is O(h); O(n) worst case and O(logn) best case. But since we are replacing the key of the deleting node by the minimum node of right sub tree of it, it will take more time to find the minimum key.
So does anybody know how to explain the time complexity in this situation?
Source Wikipedia :
Deletion
There are three possible cases to consider:
Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply remove it from the tree.
Deleting a node with one child: Remove the node and replace it with its child.
Deleting a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Copy the value of R to N, then recursively call delete on R until reaching one of the first two cases. If you choose in-order successor of a node, as right sub tree is not NIL( Our present case is node has 2 children), then its in-order successor is node with least value in its right sub tree, which will have at a maximum of 1 sub tree, so deleting it would fall in one of first 2 cases.
Deleting a node with two children from a binary search tree. First the rightmost node in the left subtree, the inorder predecessor 6, is identified. Its value is copied into the node being deleted. The inorder predecessor can then be easily deleted because it has at most one child. The same method works symmetrically using the inorder successor labelled 9.
Consistently using the in-order successor or the in-order predecessor for every instance of the two-child case can lead to an unbalanced tree, so some implementations select one or the other at different times.
Runtime analysis:
Although this operation does not always traverse the tree down to a leaf, this is always a possibility; thus in the worst case it requires time proportional to the height of the tree. It does not require more even when the node has two children, since it still follows a single path and does not visit any node twice. Hence the pointer adjustments in all three cases need constant time.
Useful Links :
http://en.wikipedia.org/wiki/Binary_search_tree#Deletion
http://cse.iitkgp.ac.in/~pb/algo-1-pb-10.pdf

Is this list a Binary Search Tree?

Is the following list a BST or not?
list:{2,5,3,8,6}
Is there a way I can determine this?
Consider that my list will have 100000 elements.
Quick answer is: no. BST is a tree and you have a list.
Long answer is: it may be possible to encode a tree as a list, in which case, whether your list can be decoded into a tree or not will depend on the encoding algorithm. See BST wiki page for more details http://en.wikipedia.org/wiki/Binary_search_tree
In fact your list may be an encoded version of BST. If you read elements from left to right pushing them onto a stack, and whenever you stack has 3 elements do:
parent = pop()
right = pop()
left = pop()
push new Node(parent, left, right)
then you should get a valid BST. But I am only speculating here.
you are having a list , you need to construct BST from this list
A BST has following properties
1- Each node has two children or it is a leaf node
2- For each node its left subtree is smaller than node's value
3- For each node its right subtree is greater than node's value
a bst MUST BE BALANCED i.e. while inserting nodes in a BST , code must respect above 3 conditions.
Searching in a BST is O(log n) operation that is because , each search step divide the search space into two halfs and choose one of the half.
There is a case where search will take O(N) time
Consider following
node = {1,2,3,4,5}
if we make the BST from this node set it will be right alifned that means every next node will be on the right subtree , here if we want to search for a item , we need to traverse whole right sub tree like a link list.

How to create a Binary Tree from a General Tree?

I have to solve the following constructor for a BinaryTree class in java:
BinaryTree(GeneralTree<T> aTree)
This method should create a BinaryTree (bt) from a General Tree (gt) as follows:
Every Vertex from gt will be represented as a leaf in bt.
If gt is a leaf, then bt will be a leaf with the same value as gt
If gt is not a leaf, then bt will be constructed as an empty root, a left subTree (lt) and a right subTree (lr). Lt is a stric binary tree created from the oldest subtree of gt (the left-most subtree) and lr is a stric binary tree created from gt without its left-most subtree.
The frist part is trivial enough, but the second one is giving me some trouble. I've gotten this far:
public BinaryTree(GeneralTree<T> aTree){
if (aTree.isLeaf()){
root= new BinaryNode<T>(aTree.getRootData());
}else{
root= new BinaryNode<T>(null); // empty root
LinkedList<GeneralTree<T>> childs = aTree.getChilds(); // Childs of the GT are implemented as a LinkedList of SubTrees
child.begin(); //start iteration trough list
BinaryTree<T> lt = new BinaryTree<T>(childs.element(0)); // first element = left-most child
this.addLeftChild(lt);
aTree.DeleteChild(hijos.elemento(0));
BinaryTree<T> lr = new BinaryTree<T>(aTree);
this.addRightChild(lr);
}
}
Is this the right way? If not, can you think of a better way to solve this? This solution, for example, gives me a bunch of nodes with no data at all, I don't know if this is an issue of the problem itself or mine.
Thank you!
The problem is that most trees cannot be validly reduced to a binary tree.
Reading your comment you are fully aware of that.
Taking for example a tree with a root node with 3 children. There is no direct way to make a binary tree out of this without sacrificing connectivity. That's where those empty nodes come from. With them, the structure of the general tree is preserved. You can reconstruct it, deleting the empty nodes and reassembling the tree from the two subtrees.
I have not debugged your code. If it does what you said it would do, it is a good solution. Empty nodes sort of store the connectivity information of the general tree. They are allowed to be there.
There is another, widely known, way to make a binary tree from a general tree, with no "connectivity nodes".
This method can be best understood like this:
Node{ Node{
data; data;
first_child; => left;
next_sibling; right;
} }
This basically represents the list of children of the general tree as a linked list, with the addition of each node having a reference to the linked list of it's children. As you can see, this is structurally equivalent to a binary tree.
So, in pseudocode (with edge cases omitted for simplicity)
BinaryTree(gtree){
root=BinaryNode(gtree.data,BinaryNode(gtree.children),null);
}
BinaryNode(List<gnode> sibs){
BinaryNode(sibs.first.data,BinaryNode(sibs.first.children),BinaryTree(sibs.rest));
}
BinaryNode(data,left,right){
data=data;
left=left;
right=right;
}
Of course, if you need to have the structure you described, this will be useless, but in general, this is a fairly good way to create a binary tree from a general tree.

Categories

Resources