I need to print the ancestors of a node in binary tree. e.g Node 7 has ancestors as 1,3 . I have written the below code but output is coming as 7. Can you suggest the issues in this code?
1
/ \
2 3
/ \ / \
4 5 6 7
public static String findAncestor(BinaryTreeNode root , int number, boolean matched) {
if (root != null) {
int rootData = root.getData();
BinaryTreeNode left = root.getLeft();
BinaryTreeNode right = root.getRight();
if (left != null && right != null) {
return findAncestor (root.getLeft(), number, matched ) + findAncestor (root.getRight(), number, matched);
}
if (left != null) {
return findAncestor (root.getLeft(), number, matched ) ;
}
if (right != null) {
return findAncestor (root.getRight(), number, matched ) ;
}
if (rootData == number) {
matched = true;
return String.valueOf(rootData);
}
if (matched) {
return String.valueOf(rootData);
}
}
return "";
}
public boolean findAncestorPath(List<Integer> ancestors, BinaryTreeNode node, int number) {
if (node == null)
return false;
int data = node.getData();
if (data == number)
return true;
if (findAncestorPath(ancestors, node.getLeft(), number)) {
ancestors.add(data);
return true;
}
if (findAncestorPath(ancestors, node.getRight(), number)) {
ancestors.add(data);
return true;
}
return false;
}
Then you'd call this as (you should also probably wrap it in a function):
List<Integer>() ancestors = new ArrayList<Integer>();
boolean found = findAncestorPath(ancestors, root, number);
Note that the ancestor list would be reversed.
Here is the Java implementation
public static List<Integer> ancestors(BinaryTreeNode<Integer> root, Integer target) {
List<Integer> result = new ArrayList<Integer>();
findAncestors(root, target, result);
return result;
}
private static boolean findAncestors(BinaryTreeNode<Integer> node, Integer target, List<Integer> result) {
if (node == null) {
return false;
}
if (node.getData() == target) {
return true;
}
if (findAncestors(node.getLeft(), target, result) || findAncestors(node.getRight(), target, result)) {
result.add(node.getData());
return true;
}
return false;
}
Here is the unit test case
#Test
public void allAncestors() {
BinaryTreeNode<Integer> root = buildTree();
List<Integer> ancestors = BinaryTreeUtil.ancestors(root, 6);
assertThat(ancestors.toArray(new Integer[0]), equalTo(new Integer[]{5,2,1}));
}
This piece of code work fine for giving all the ancestors a particular node , node is root node and value is the value of the node for which we have to find all the ancestor.
static boolean flag=false;
static void AnchersterOf(AnchesterNode node,int value) {
// TODO Auto-generated method stub
if(node==null)
return ;
if(node.value==value){
flag=true;
return;
}
if(flag==false){
AnchersterOf(node.left,value);
if(flag==true){
AnchersterOf(node,value);
} if(flag==true)
System.out.println(node.value);
AnchersterOf(node.right,value);
if(flag==true)
System.out.println(node.value);
}
}
Related
I'm trying to write a function that displays the height of my binary search tree which is displayed below. The problem is I'm supposed to write a function that doesn't have any arguments or parameters. This is really stumping me. I tried declaring root outside the parameter list but that didn't work. Any solutions?
int height (Node root){
if (root == null) {
return 0;
}
int hleftsub = height(root.m_left);
int hrightsub = height(root.m_right);
return Math.max(hleftsub, hrightsub) + 1;
}
the method signature provide by my instructor is
int height ()
EDIT:
my full code
import javax.swing.tree.TreeNode;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
class BinarySearchTree<E extends Comparable<E>> {
public Node<E> root;
public int m_size = 0;
public BinarySearchTree() {
}
public boolean search(E value) {
boolean ret = false;
Node<E> current = root;
while (current != null && ret != true) {
if (current.m_value.compareTo(current.m_value) == 0) {
ret = true;
} else if (current.m_value.compareTo(current.m_value) > 0) {
current = current.m_left;
} else {
current = current.m_right;
}
}
return false;
}
public boolean insert(E value) {
if (root == null) {
root = new Node<>(value);
m_size++;
} else {
Node<E> current = root;
Node<E> parentNode = null;
while (current != null)
if (current.m_value.compareTo(value) > 0) {
parentNode = current;
current = current.m_left;
} else if (current.m_value.compareTo(value) < 0) {
parentNode = current;
current = current.m_right;
} else {
return false;
}
if (current.m_value.compareTo(value) < 0) {
parentNode.m_left = new Node<>(value);
} else {
parentNode.m_right = new Node<>(value);
}
}
m_size++;
return true;
}
boolean remove(E value) {
if (!search(value)) {
return false;
}
Node check = root;
Node parent = null;
boolean found = false;
while (!found && check != null) {
if (value.compareTo((E) check.m_value) == 0) {
found = true;
} else if (value.compareTo((E) check.m_value) < 0) {
parent = check;
check = check.m_left;
} else {
parent = check;
check = check.m_right;
}
}
if (check == null) {
return false;
} else if (check.m_left == null) {
if (parent == null) {
root = check.m_right;
} else if (value.compareTo((E) parent.m_value) < 0) {
parent.m_left = check.m_right;
} else {
parent.m_right = check.m_right;
}
} else {
Node<E> parentofRight = check;
Node<E> rightMost = check.m_left;
while (rightMost.m_right != null) {
parentofRight = rightMost;
rightMost = rightMost.m_right;
}
check.m_value = rightMost.m_value;
if (parentofRight.m_right == rightMost) {
rightMost = rightMost.m_left;
} else {
parentofRight.m_left = rightMost.m_left;
}
}
m_size--;
return true;
}
int numberNodes () {
return m_size;
}
int height (Node root){
if (root == null) {
return 0;
}
int hleftsub = height(root.m_left);
int hrightsub = height(root.m_right);
return Math.max(hleftsub, hrightsub) + 1;
}
int numberLeafNodes(Node node){
if (node == null) {
return 0;
}
else if(node.m_left == null && node.m_right == null){
return 1;
}
else{
return numberLeafNodes(node.m_left) + numberLeafNodes(node.m_right);
}
}
void display(String message){
if(root == null){
return;
}
display(String.valueOf(root.m_left));
display(String.valueOf(root));
display(String.valueOf(root.m_right));
}
}
class Node<E> {
public E m_value;
public Node<E> m_left;
public Node<E> m_right;
public Node(E value) {
m_value = value;
}
}
If you traverse the tree iteratively, you can get the height without recursion. Anything recursive can be implemented iteratively. It may be more lines of code though. This would be a variation of level order graph / tree traversal.
See: https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/
If you use that implementation, delete the parameter, as height() will already have access to root.
This however requires a queue and is O(n) time and O(n) space.
height() may be a public method that calls a private method height(Node node) that starts recursion. O(n) time, O(1) space for BST.
You can pass height as an extra parameter where recursively inserting into the tree so that you are counting the number of recursive calls (which is directly correlated with the depth / # of levels down in the tree you are). Once a node finds it's place, if the height (# of recursive calls) you were passing exceeds the instance variable height stored by the tree, you update the instance variable to the new height. This will also allow tree.height() to be a constant time function. O(1) time, O(1) space.
I am trying to return the data held by the nth item of a BST, I'm trying to do an inorder traversal with a counter, and when the counter is larger than n, return the current node. My current code seems to always return the first item, and I can't see where my logic is wrong. I only wrote the nth and inOrder methods, the rest were provided. I think I'm incrementing my counter too often, is that the cause or am I doing something else wrong. I'll post the main method I'm testing with below as well.
import java.util.NoSuchElementException;
public class BST {
private BTNode<Integer> root;
public BST() {
root = null;
}
public boolean insert(Integer i) {
BTNode<Integer> parent = root, child = root;
boolean goneLeft = false;
while (child != null && i.compareTo(child.data) != 0) {
parent = child;
if (i.compareTo(child.data) < 0) {
child = child.left;
goneLeft = true;
} else {
child = child.right;
goneLeft = false;
}
}
if (child != null)
return false; // number already present
else {
BTNode<Integer> leaf = new BTNode<Integer>(i);
if (parent == null) // tree was empty
root = leaf;
else if (goneLeft)
parent.left = leaf;
else
parent.right = leaf;
return true;
}
}
public int greater(int n) {
if (root == null) {
return 0;
}
else {
return n;
}
}
int c = 0;
public int nth(int n) throws NoSuchElementException {
BTNode<Integer> node = null;
if (root == null) {
throw new NoSuchElementException("Element " + n + " not found in tree");
}
else {
if (root != null){
node = inOrder(root, n);
}
}
return node.data;
}
public BTNode inOrder(BTNode<Integer> node, int n) {
c++;
while (c <= n) {
if (node.left != null) {
inOrder(node.left, n);
}
c++;
if (node.right != null) {
inOrder(node.right, n);
}
}
return node;
}
}
class BTNode<T> {
T data;
BTNode<T> left, right;
BTNode(T o) {
data = o;
left = right = null;
}
}
public class bstTest {
public static void main(String[] args) {
BST tree = new BST();
tree.insert(2);
tree.insert(5);
tree.insert(7);
tree.insert(4);
System.out.println(tree.nth(2));
}
}
An invariant you should consider is that when n = sizeOfLeftSubtree + 1, then return that node. If n is less, then go left. If n is greater, then go right and reduce n by sizeOfLeftSubtree+1. Note that I map n=1 to the first element (the leftmost element).
You could trivially calculate the size of a subtree recursively, or you can store the size at every root (every node is a root of a subtree) modifying you insert method (save in a stack/queue all nodes visited and if a new node is added just increment all sizes by 1).
If the size is stored the complexity will be O(log n). If not if could become O(n^2).
public int nth(int n) throws NoSuchElementException {
if( sizeOfTree(this.root) < n || n < 1)
throw new NoSuchElementException("Element " + n + " not found in tree");
BTNode<Integer> root = this.root;
boolean found = false;
do{
int sizeOfLeftSubtree = sizeOfTree(root.left);
if( sizeOfLeftSubtree + 1 == n ){
found = true;
}else if( n < sizeOfLeftSubtree+1 ){
root = root.left;
}else if( sizeOfLeftSubtree+1 < n ){
root = root.right;
n -= sizeOfLeftSubtree+1;
}
}while( !found );
return root.data;
}
public int sizeOfTree(BTNode<Integer> root){
if( root == null )
return 0;
else
return sizeOfTree(root.left) + 1 + sizeOfTree(root.right);
}
You don't change node in the inOrder method.
public BTNode inOrder(BTNode<Integer> node, int n) {
c++;
while (c <= n) {
if (node.left != null) {
// **** Add this - or something.
node = inOrder(node.left, n);
}
c++;
if (node.right != null) {
// **** Add this - or something.
node = inOrder(node.right, n);
}
}
return node;
}
Not suggesting this is the bug you are trying to fix but it is certainly a problem with the code.
I have a program that is a binary search tree, the method searches for a specific word. I'm having two problems.
First is I would like to print the true or false from this method (basically making a system.out that says if the word was found), I'm assuming I would do it in main but I'm not sure how to do that.
The second problem is that I also need to print out how many leaves are in the tree, I was going to use a counter of some sort in the method but I didn't work.
My method is below but I also included it inside the class to help clear up any confusion.
Any help would be greatly appreciated.
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
Whole class:
public class BST
{
BSTNode root;
BST() {
root = null;
}
public void add2Tree(String st)
{
BSTNode newNode = new BSTNode(st);
if (this.root == null) {
root = newNode;
} else {
root = addInOrder(root, newNode);
}
}
// private BSTNode insert2(BSTNode root, BSTNode newNode)
// {
// if (root == null)
// root = newNode;
// else {
// System.out.println(root.word + " " + newNode.word);
// if (root.word.compareTo(newNode.word) > 0)
// {
// root.left = (insert2(root.lTree, newNode));
// System.out.println(" left ");
// } else
// {
// root.rTree = (insert2(root.rTree, newNode));
// System.out.println(" right ");
// }
// }
// return root;
// }
public BSTNode addInOrder(BSTNode focus, BSTNode newNode) {
int comparevalue = 0;
if (focus == null) {
focus = newNode;
}
if (focus != null) {
comparevalue = newNode.word.compareTo(focus.word);
}
if (comparevalue < 0) {
focus.left = addInOrder(focus.left, newNode);
} else if (comparevalue > 0) {
focus.right = addInOrder(focus.right, newNode);
}
return (focus);
}
public void ioprint() {
System.out.println(" start inorder");
if (root == null)
System.out.println(" Null");
printinorder(root);
}
public void printinorder(BSTNode t) {
if (t != null) {
printinorder(t.left);
System.out.println(t.word);
printinorder(t.right);
}
}
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
public BSTNode getroot(){
return root;
}
}
How to print true/false:
Create another class, call it Solution, Test or whatever you like.
Add a main method to it.
Populate your BST.
Call System.out.println(check(bstRoot, key)).
You can check this link to find out how to count the number of nodes in BST, it's pretty straightforward:
Counting the nodes in a binary search tree
private int countNodes(BSTNode current) {
// if it's null, it doesn't exist, return 0
if (current == null) return 0;
// count myself + my left child + my right child
return 1 + nodes(current.left) + nodes(current.right);
}
I wrote the following codes for implementation of Binary Search Tree in JAVA. Everything seems to be working fine except the Search Method. Each Node has a key (Item) ,an Object of type string and a reference to left and right node.
class BinarySearchTree1
{
class Node // Node for BST
{
private int item;
private String obj;
private Node left;
private Node right;
Node(int Item,String Obj)
{
item = Item;
obj = Obj;
left = null;
right = null;
}
}
Node root; //Root of the BST
BinarySearchTree1() // Constructor
{
root = null;
}
void insert(int key,String obj) // Insertion
{
root = insertItem(root,key,obj);
}
Node insertItem(Node root,int key,String obj)
{
if(root == null)
{
root = new Node(key,obj);
return root;
}
else if(key>root.item)
root.right = insertItem(root.right,key,obj);
else
root.left = insertItem(root.left,key,obj);
return root;
}
void inOrder() // View Records in order
{
System.out.println("List: ");
inOrderRec(root);
}
void inOrderRec(Node root)
{
if(root != null)
{
inOrderRec(root.left);
System.out.println(root.item + " "+ root.obj);
inOrderRec(root.right);
}
}
void search(int key) // Search
{
Node Temp;
Temp = root;
Temp = searchRec(Temp,key);
if(Temp == null) // Element Not Found
{
System.out.println("Object for "+key+" NOT FOUND");
return;
}
System.out.println("Object for "+ Temp.item+" is "+ Temp.obj); // Element Found
}
Node searchRec(Node Temp,int key)
{
if(Temp != null)
{
if(key>Temp.item)
{
Temp.right = searchRec(Temp.right,key);
return Temp.right;
}
if(key<Temp.item)
{
Temp.left = searchRec(Temp.left,key);
return Temp.left;
}
if(key==Temp.item)
return Temp;
}
return Temp;
}
public static void main(String[] args)
{
BinarySearchTree1 b1 = new BinarySearchTree1();
b1.insert(6,"a");
b1.insert(7,"aa");
b1.insert(4,"aaa");
b1.insert(1,"aaaa");
b1.insert(9,"b");
b1.insert(8,"bb");
b1.inOrder();
b1.search(9);
b1.search(1);
b1.inOrder();
b1.search(8);
b1.search(4);
//System.out.println(b1.root.obj);
}
}
The following code outputs:
List:
1 aaaa
4 aaa
6 a
7 aa
8 bb
9 b
Object for 9 is b
Object for 1 is aaaa
List:
1 aaaa
6 a
8 bb
9 b
Object for 8 is bb
Object for 4 NOT FOUND\
Its clear that the elements with keys 4 and 7 aren't there anymore. Can anyone explain this?
It should be:
Node searchRec(Node Temp, int key) {
if (Temp != null) {
Node t = null;
if (key > Temp.item) {
t = searchRec(Temp.right, key);
return t;
}
if (key < Temp.item) {
t = searchRec(Temp.left, key);
return t;
}
if (key == Temp.item)
return Temp;
}
return Temp;
}
you were updating nodes in this methods which will break node links.
Temp.right = searchRec(Temp.right, key); // wrong
Temp.left = searchRec(Temp.left, key); // wrong
Update:
You can replace:
t = searchRec(Temp.right, key);
return t;
with this also
return searchRec(Temp.right,key);
same way with left and this will not require any temporary variable.
Node searchRec(Node Temp,int key)
{
if(Temp != null)
{
if(key>Temp.item)
{
return searchRec(Temp.right,key);
}
if(key<Temp.item)
{
return searchRec(Temp.left,key);
}
if(key==Temp.item)
return Temp;
}
return Temp;
}
I want to write a method that would record all positions of nodes of haystack starting from where the pattern (structure) of itself matches as that of the needle. The value stored in the node doesn't need to be equal, its just the pattern that is supposed to match.
Illustration
Example 1
If I have the following haystack and needle
In the example above, the program is expected to record
ROOT
ROOT->Left
Example 2
If I have the same haystack as that of above and my needle as
Then my program is expected to record,
ROOT
ROOT->Left
ROOT->Right
However, it seems like the way I am implementing my code is flawed because my method even records positions that shouldn't have been true.
The way I am implementing my code is, I have the following method that would return a list which contains all such positions and I am using a isSubtree method to check if the pattern starting from a particular node finds a match.
public static List<String> searchForNeedleInHaystack(Node haystack,
Node needle) {
List<String> resultList = new ArrayList<String>();
if(haystack.getLeftChild() != null) {
value = value + "L";//value is just a global string variable initially ""
if(isSubtree(haystack.getLeftChild(), needle)) {
resultList.add(value);
} else {
if(value.length() > 1)
value = value.substring(0, value.length() - 1);
}
searchForNeedleInHaystack(haystack.getLeftChild(), needle);
}
if(haystack.getRightChild() != null) {
value = value + "R";
if(isSubtree(haystack.getRightChild(), needle)) {
resultList.add(value);
} else {
if(value.length() > 1)
value = value.substring(0, value.length() - 1);
}
searchForNeedleInHaystack(haystack.getRightChild(), needle);
}
return resultList;
}
public static boolean isSubtree(Node haystack, Node needle) {
if(needle == null)
return true;
if(haystack == null)
return false;
return isSubtree(haystack.getLeftChild(), needle.getLeftChild()) && isSubtree(haystack.getRightChild(), needle.getRightChild());
}
Node class
public class Node {
private String info;
private Node leftChild = null;
private Node rightChild = null;
public Node() {
this("");
}
public Node(String info) {
this.info = info;
}
public void setinfo(String info) {
this.info = info;
}
public void setLeftChild(Node n) {
leftChild = n;
}
public void setRightChild(Node n) {
rightChild = n;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public String getinfo() {
return info;
}
public boolean isLeaf() {
return rightChild == null && leftChild == null;
}
}
Problem
I just wanted to know what logic could I perhaps use so that I can compare for subtree structures successfully?
Thanks in advance!