Deletion in Binary search tree in java - binary-search-tree

Why am I not able to delete the desired node ?. For example if I construct a tree with entries in this order 1,2,3,4,5 and use my delete method to delete 3 then the nodes containing 3 and less will be deleted instead of only 3 and I shall get 4,5 if I again print all the nodes in preorder.Please help.
import java.util.Scanner;
class tnode {
protected int data;
protected tnode left,right;
public tnode(){
data=0;
right=left=null;
}
public tnode(int v){
data=v;
right=left=null;
}
public int getdata(){
return data;
}
public tnode getleft(){
return left;
}
public tnode getright(){
return right;
}
}
class btree{
protected tnode root;
public btree(){
root=null;
}
public boolean isEmpty(){
return root==null;
}
public void insert(int val){
root=insert(root,val);
}
private tnode insert(tnode r,int val){
if(r==null){
r=new tnode(val);
}
else{
if(val>r.getdata()){
r.right=insert(r.right,val);
}
else{
r.left=insert(r.left,val);
}
}
return r;
}
public void preorder(){
preorder(root);
}
private void preorder(tnode r){
if(r!=null){
System.out.print(r.getdata()+" ");
preorder(r.getleft());
preorder(r.getright());
}
}
public int min(){
return min(root);
}
public int min(tnode r){
if(r.left==null){
return r.getdata();
}
else{
return min(r.left);
}
}
public void delete(int val){
root=delete(root,val);
}
private tnode delete(tnode r,int val){
if(r==null){
return null;
}
else if( val>r.getdata()){
r=delete(r.right,val);
}
else if(val<r.getdata()){
r=delete(r.left,val);
}
else{// when r.data=value
//if node has both children
if(r.left!=null && r.right!=null){
tnode temp=r;
//get the minimum value in right sub tree
int min_right=min(temp.right);
//replace this with the node to be deleted
r.data=min_right;
//delete this node
r=delete(r.right,min_right);
}
//if has left child
else if(r.left!=null){
r=r.left;
}
//if has right child
else if(r.right!=null){
r=r.right;
}
else{
//if has no child
r=null;
}
}
return r;
}
}

private tnode delete(tnode r,int val){
if(r==null){
return null;
}
else if( val>r.getdata()){
r=delete(r.right,val); //it should be r.right=delete(r.right,val);
}
else if(val<r.getdata()){
r=delete(r.left,val); //it should be r.left=delete(r.left,val);
}
else{// when r.data=value
//if node has both children
if(r.left!=null && r.right!=null){
tnode temp=r;
//get the minimum value in right sub tree
int min_right=min(temp.right);
//replace this with the node to be deleted
r.data=min_right;
//delete this node
r.right=delete(r.right,min_right);
}
//if has left child
else if(r.left!=null){
r=r.left;
}
//if has right child
else if(r.right!=null){
r=r.right;
}
else{
//if has no child
r=null;
}
}
return r;
}

Related

How to move the snap position from center to left of RecycleView using SnapHelper?

I have an RecycleView that contains ImageViews and my question is how can i move the snap to be on the left side of the RecycleView instead of the center?
When i move the ImageViews they get snapped in the center and I can move them to the left or right inside that "snap window" by overriding the CalculateDistanceToFinalSnap method. I think I would now need to move that "snap window" to the left side of the RecycleView but I don't know how, or maybe there is another way, please help.
Here is a image of my problem, maybe it will help you to understand more clearly:
image
#Jessie Zhang -MSFT's solution works for me. The code was a little oddly formatted and I had some difficulty bringing it over. Here is the same solution (for a horizontal snap only) in Kotlin.
class StartSnapHelper: LinearSnapHelper() {
override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager, targetView: View): IntArray? {
return if (layoutManager.canScrollHorizontally()) {
val outer = mutableListOf<Int>()
outer.add(distanceToStart(targetView, getHorizontalHelper(layoutManager)))
outer.add(0)
outer.toIntArray()
} else {
super.calculateDistanceToFinalSnap(layoutManager, targetView)
}
}
override fun findSnapView(layoutManager: RecyclerView.LayoutManager?): View? {
return if (layoutManager is LinearLayoutManager) {
if (layoutManager.canScrollHorizontally()) {
getStartView(layoutManager, getHorizontalHelper(layoutManager))
} else {
super.findSnapView(layoutManager)
}
} else {
super.findSnapView(layoutManager)
}
}
private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
return helper.getDecoratedStart(targetView) - helper.startAfterPadding
}
private fun getStartView(layoutManager: RecyclerView.LayoutManager, orientationHelper: OrientationHelper): View? {
val firstChild = (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
val isLastItem = (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.itemCount - 1)
if (firstChild == RecyclerView.NO_POSITION || isLastItem) {
return null
}
val child = layoutManager.findViewByPosition(firstChild)
return if (orientationHelper.getDecoratedEnd(child) >= orientationHelper.getDecoratedMeasurement(child) / 2
&& orientationHelper.getDecoratedEnd(child) > 0) {
child;
} else {
if (layoutManager.findFirstCompletelyVisibleItemPosition() == layoutManager.itemCount -1) {
null
} else {
layoutManager.findViewByPosition(firstChild + 1)
}
}
}
private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
return OrientationHelper.createHorizontalHelper(layoutManager)
}
}
I have achieved this function ,we juse need to create a class and extent class LinearSnapHelper and override method CalculateDistanceToFinalSnap and FindSnapView. You can check out the full demo here .
The main code is as follows:
public class StartSnapHelper: LinearSnapHelper
{
private OrientationHelper mVerticalHelper, mHorizontalHelper;
public StartSnapHelper()
{
}
public override void AttachToRecyclerView(RecyclerView recyclerView)
{
base.AttachToRecyclerView(recyclerView);
}
public override int[] CalculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView)
{
//return base.CalculateDistanceToFinalSnap(layoutManager, targetView);
int[] outer = new int[2];
if (layoutManager.CanScrollHorizontally())
{
outer[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
} else {
outer[0] = 0;
}
if (layoutManager.CanScrollVertically()) {
outer[1] = distanceToStart(targetView, getVerticalHelper(layoutManager));
} else {
outer[1] = 0;
}
return outer;
}
private int distanceToStart(View targetView, OrientationHelper helper)
{
return helper.GetDecoratedStart(targetView) - helper.StartAfterPadding;
}
public override View FindSnapView(RecyclerView.LayoutManager layoutManager)
{
if (layoutManager is LinearLayoutManager) {
if (layoutManager.CanScrollHorizontally())
{
return getStartView(layoutManager, getHorizontalHelper(layoutManager));
}
else
{
return getStartView(layoutManager, getVerticalHelper(layoutManager));
}
}
return base.FindSnapView(layoutManager);
}
private View getStartView(RecyclerView.LayoutManager layoutManager,
OrientationHelper helper)
{
if (layoutManager is LinearLayoutManager) {
int firstChild = ((LinearLayoutManager)layoutManager).FindFirstVisibleItemPosition();
bool isLastItem = ((LinearLayoutManager)layoutManager)
.FindLastCompletelyVisibleItemPosition()
== layoutManager.ItemCount - 1;
if (firstChild == RecyclerView.NoPosition || isLastItem)
{
return null;
}
View child = layoutManager.FindViewByPosition(firstChild);
if (helper.GetDecoratedEnd(child) >= helper.GetDecoratedMeasurement(child) / 2
&& helper.GetDecoratedEnd(child) > 0)
{
return child;
}
else
{
if (((LinearLayoutManager)layoutManager).FindLastCompletelyVisibleItemPosition()
== layoutManager.ItemCount - 1)
{
return null;
}
else
{
return layoutManager.FindViewByPosition(firstChild + 1);
}
}
}
return base.FindSnapView(layoutManager);
}
private OrientationHelper getVerticalHelper(RecyclerView.LayoutManager layoutManager)
{
if (mVerticalHelper == null)
{
mVerticalHelper = OrientationHelper.CreateVerticalHelper(layoutManager);
}
return mVerticalHelper;
}
private OrientationHelper getHorizontalHelper(RecyclerView.LayoutManager layoutManager)
{
if (mHorizontalHelper == null)
{
mHorizontalHelper = OrientationHelper.CreateHorizontalHelper(layoutManager);
}
return mHorizontalHelper;
}
}
And use like this:
SnapHelper snapHelperStart = new StartSnapHelper();
snapHelperStart.AttachToRecyclerView(recyclerView);

Generic BST having trouble getting constructor to work

I have been given some code from my instructor and i need to implement several functions. I have added the insert method but I can not figure out how or what the constructor is looking for, I don't understand why this call to construct a tree is not working. Not very strong in java but understand the logic of a BST
public class BinaryTreeDriver {
public static void main(String[] args){
BinaryTree<Integer> numbers = new BinaryTree<>();
I am getting compiler error cannot infer type arguments BinaryTree<>
Copying rest of code below
public class BinaryTree<T extends Comparable<T>> {
private BinaryTreeNode<T> root; // the root of the tree
private BinaryTreeNode<T> cursor; // the current node
/**
* Constructor for initializing a tree with node
* being set as the root of the tree.
* #param node
*/
public BinaryTree(BinaryTreeNode<T> node) {
root = node;
}
/**
* Moves the cursor to the root.
*/
public void toRoot() {
cursor = root;
}
/**
* Returns the cursor node.
* #return cursor
*/
public BinaryTreeNode<T> getCursor() {
return cursor;
}
/**
* Sets the root to the provided node.
* ONLY USE IN THE DELETE METHOD
* #param node
*/
public void setRoot(BinaryTreeNode<T> node) {
root = node;
}
/**
* Checks if the tree node has a left child node
* #return true if left child exists else false
*/
public boolean hasLeftChild() {
return cursor.getLeft() != null;
}
/**
* Checks if the tree node has a right child node
* #return true if right child exists else false
*/
public boolean hasRightChild() {
return cursor.getRight() != null;
}
/**
* Move the cursor to the left child
*/
public void toLeftChild() {
cursor = cursor.getLeft();
}
/**
* Move the cursor to the right child
*/
public void toRightChild() {
cursor = cursor.getRight();
}
/**
* #return height of the tree
*/
public int height() {
if (root != null) {
return root.height();
} else {
return 0;
}
}
**/**
* Tree-Insert
*/
public boolean insert(T elem)
{
return insert(root, elem);
}
public boolean insert(BinaryTreeNode start, T elem)
{
if (start == null)
{
root = new BinaryTreeNode<T>(elem, null, null);
return true;
}
int comparison = start.getData().compareTo(elem);
if (comparison > 0)
{
if (start.getLeft() == null)
{
start.setLeft(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getLeft(), elem);
}
else if (comparison < 0)
{
if (start.getRight() == null)
{
start.setRight(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getRight(), elem);
}
else
{
return false;
}**
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
public String toString() {
if (root != null) {
return root.toStringPreOrder(".");
} else {
return "";
}
}
}
public class BinaryTreeNode<T extends Comparable<T>> {
private BinaryTreeNode<T> left; // the left child
private BinaryTreeNode<T> right; // the right child
private T data; // the data in this node
public BinaryTreeNode() {
this(null, null, null);
}
public BinaryTreeNode(T theData) {
this(theData, null, null);
}
public BinaryTreeNode(T theData, BinaryTreeNode<T> leftChild,
BinaryTreeNode<T> rightChild) {
data = theData;
left = leftChild;
right = rightChild;
}
public T getData() {
return data;
}
public BinaryTreeNode<T> getLeft() {
return left;
}
public BinaryTreeNode<T> getRight() {
return right;
}
public void setLeft(BinaryTreeNode<T> newLeft) {
left = newLeft;
}
public void setRight(BinaryTreeNode<T> newRight) {
right = newRight;
}
public void setData(T newData) {
data = newData;
}
public void preOrder() {
System.out.println(data);
if (left != null) {
left.preOrder();
}
if (right != null) {
right.preOrder();
}
}
public int height() {
int leftHeight = 0; // Height of the left subtree
int rightHeight = 0; // Height of the right subtree
int height = 0; // The height of this subtree
// If we have a left subtree, determine its height
if (left != null) {
leftHeight = left.height();
}
// If we have a right subtree, determine its height
if (right != null) {
rightHeight = right.height();
}
// The height of the tree rooted at this node is one more than the
// height of the 'taller' of its children.
if (leftHeight > rightHeight) {
height = 1 + leftHeight;
} else {
height = 1 + rightHeight;
}
// Return the answer
return height;
}
/**
* #param pathString
* #return the tree nodes in pre-order traversal
*/
public String toStringPreOrder(String pathString) {
String treeString = pathString + " : " + data + "\n";
if (left != null) {
treeString += left.toStringPreOrder(pathString + "L");
}
if (right != null) {
treeString += right.toStringPreOrder(pathString + "R");
}
return treeString;
}
}

Qt TableView only sorting once

I have a QTableView that is populated with a QSqlQueryModel. I am trying to sort the table based on which RadioButton is checked, but nothing is happening when I press them. There was one point where I could get it to sort, but only once. What am I doing wrong here?
void MainWindow::on_openButton_clicked()
{
QString filePath = ui->lineEdit->text();
if( filePath != "" ){
if( openDB( filePath ) ){
ui->debugLabel->setText("Database opened");
MainWindow::populateTable();
}else{
ui->debugLabel->setText("Unable to open database");
}
} else {
ui->debugLabel->setText("Path is empty");
}
}
void MainWindow::populateTable(){
if( readDB() ){
ui->tableView->setModel(toast.dbModel);
}
}
void MainWindow::on_shootButton_toggled(bool checked)
{
if( checked ){
ui->tableView->sortByColumn( 0 );
}
}
void MainWindow::on_winButton_toggled(bool checked)
{
if( checked ){
ui->tableView->sortByColumn( 1 );
}
}
bool openDB(QString path){
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(path);
return db.open();
}
bool readDB(){
if( db.isOpen() ){
dbModel->setQuery( "select * from test", db );
return true;
} else {
return false;
}
}
QSqlQueryModel isn't sortable by default, QSqlTableModel is sortable but there's differences between the two. You can make QSqlQueryModel sortable by inheriting the class and reimplementing the sort() method though, if you have a look at the documentation for QAbstractItemModel it'll give you some details about it.

Class is CLS Compliant to .NET but not in Mono

I had to build my own Version class. In .NET it's CLS Compliant but in Mono its not for some reason. Any ideas why?
[Serializable]
public class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version>
{
private int major;
private int minor;
private int revision;
private int build;
protected Version()
{
}
public Version(int major, int minor)
{
Major = major;
Minor = minor;
}
public Version(int major, int minor, int revision, int build) : this(major, minor)
{
Revision = revision;
Build = build;
}
public Version(string version)
{
if (string.IsNullOrWhiteSpace(version))
{
throw new ControlInfluence.Exceptions.ArgumentNullStringException("version");
}
string[] parts = version.Split('.');
if ((parts.Length != 4) && (parts.Length != 2))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[0], out major))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[1], out minor))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[2], out revision))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
if (!int.TryParse(parts[3], out build))
{
throw new ArgumentException("'version' must have 2 or 4 numbers separated by '.'.", "version");
}
}
public int Major
{
get
{
return major;
}
set
{
major = value;
}
}
public int Minor
{
get
{
return minor;
}
set
{
minor = value;
}
}
public int Build
{
get
{
return build;
}
set
{
build = value;
}
}
public int Revision
{
get
{
return revision;
}
set
{
revision = value;
}
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", Major, Minor, Revision, Build);
}
public static bool operator <(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return left.CompareTo(right) < 0;
}
public static bool operator >(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return left.CompareTo(right) > 0;
}
#region ICloneable Members
public object Clone()
{
return new Version(Major, Minor, Revision, Build);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
Version other = obj as Version;
if (other == null)
{
return -1;
}
return CompareTo(other);
}
#endregion
#region IComparable<Version> Members
public int CompareTo(Version other)
{
if (other == null)
{
return -1;
}
int compareMajor = Major.CompareTo(other.Major);
if (compareMajor != 0)
{
return compareMajor;
}
int compareMinor = Minor.CompareTo(other.Minor);
if (compareMinor != 0)
{
return compareMinor;
}
int compareRevision = Revision.CompareTo(other.Revision);
if (compareRevision != 0)
{
return compareRevision;
}
return Build.CompareTo(other.Build);
}
#endregion
#region IEquatable<Version> Members
public bool Equals(Version other)
{
return CompareTo(other) == 0;
}
#endregion
public override bool Equals(object obj)
{
Version version = obj as Version;
if (version == null)
{
return false;
}
return Equals(version);
}
public static bool operator ==(Version left, Version right)
{
if (Object.ReferenceEquals(left, null) && Object.ReferenceEquals(right, null))
{
return true;
}
if (Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null))
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(Version left, Version right)
{
if ((left == null) || (right == null))
{
return false;
}
return !left.Equals(right);
}
}
The custom exception classes I throw are simply wrappers around ArgumentNullException that "auto fill" the message for me so they aren't adding any types to it really.
If it's CLS compliant in .NET but not on Mono, it is a bug in Mono. Please file a bug in http://bugzilla.xamarin.com

Exporting a non public Type through public API

I am trying to follow Trees tutorial at: http://cslibrary.stanford.edu/110/BinaryTrees.html
Here is the code I have written so far:
package trees.bst;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* #author sachin
*/
public class BinarySearchTree {
Node root = null;
class Node {
Node left = null;
Node right = null;
int data = 0;
public Node(int data) {
this.left = null;
this.right = null;
this.data = data;
}
}
public void insert(int data) {
root = insert(data, root);
}
public boolean lookup(int data) {
return lookup(data, root);
}
public void buildTree(int numNodes) {
for (int i = 0; i < numNodes; i++) {
int num = (int) (Math.random() * 10);
System.out.println("Inserting number:" + num);
insert(num);
}
}
public int size() {
return size(root);
}
public int maxDepth() {
return maxDepth(root);
}
public int minValue() {
return minValue(root);
}
public int maxValue() {
return maxValue(root);
}
public void printTree() { //inorder traversal
System.out.println("inorder traversal:");
printTree(root);
System.out.println("\n--------------");
}
public void printPostorder() { //inorder traversal
System.out.println("printPostorder traversal:");
printPostorder(root);
System.out.println("\n--------------");
}
public int buildTreeFromOutputString(String op) {
root = null;
int i = 0;
StringTokenizer st = new StringTokenizer(op);
while (st.hasMoreTokens()) {
String stNum = st.nextToken();
int num = Integer.parseInt(stNum);
System.out.println("buildTreeFromOutputString: Inserting number:" + num);
insert(num);
i++;
}
return i;
}
public boolean hasPathSum(int pathsum) {
return hasPathSum(pathsum, root);
}
public void mirror() {
mirror(root);
}
public void doubleTree() {
doubleTree(root);
}
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
public void printPaths() {
if (root == null) {
System.out.println("print path sum: tree is empty");
}
List pathSoFar = new ArrayList();
printPaths(root, pathSoFar);
}
///-------------------------------------------Public helper functions
public Node getRoot() {
return root;
}
//Exporting a non public Type through public API
///-------------------------------------------Helper Functions
private boolean isLeaf(Node node) {
if (node == null) {
return false;
}
if (node.left == null && node.right == null) {
return true;
}
return false;
}
///-----------------------------------------------------------
private boolean sameTree(Node n1, Node n2) {
if ((n1 == null && n2 == null)) {
return true;
} else {
if ((n1 == null || n2 == null)) {
return false;
} else {
if ((n1.data == n2.data)) {
return (sameTree(n1.left, n2.left) && sameTree(n1.right, n2.right));
}
}
}
return false;
}
private void doubleTree(Node node) {
//create a copy
//bypass the copy to continue looping
if (node == null) {
return;
}
Node copyNode = new Node(node.data);
Node temp = node.left;
node.left = copyNode;
copyNode.left = temp;
doubleTree(copyNode.left);
doubleTree(node.right);
}
private void mirror(Node node) {
if (node == null) {
return;
}
Node temp = node.left;
node.left = node.right;
node.right = temp;
mirror(node.left);
mirror(node.right);
}
private void printPaths(Node node, List pathSoFar) {
if (node == null) {
return;
}
pathSoFar.add(node.data);
if (isLeaf(node)) {
System.out.println("path in tree:" + pathSoFar);
pathSoFar.remove(pathSoFar.lastIndexOf(node.data)); //only the current node, a node.data may be duplicated
return;
} else {
printPaths(node.left, pathSoFar);
printPaths(node.right, pathSoFar);
}
}
private boolean hasPathSum(int pathsum, Node node) {
if (node == null) {
return false;
}
int val = pathsum - node.data;
boolean ret = false;
if (val == 0 && isLeaf(node)) {
ret = true;
} else if (val == 0 && !isLeaf(node)) {
ret = false;
} else if (val != 0 && isLeaf(node)) {
ret = false;
} else if (val != 0 && !isLeaf(node)) {
//recurse further
ret = hasPathSum(val, node.left) || hasPathSum(val, node.right);
}
return ret;
}
private void printPostorder(Node node) { //inorder traversal
if (node == null) {
return;
}
printPostorder(node.left);
printPostorder(node.right);
System.out.print(" " + node.data);
}
private void printTree(Node node) { //inorder traversal
if (node == null) {
return;
}
printTree(node.left);
System.out.print(" " + node.data);
printTree(node.right);
}
private int minValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.left == null) {
return node.data;
} else {
return minValue(node.left);
}
}
private int maxValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.right == null) {
return node.data;
} else {
return maxValue(node.right);
}
}
private int maxDepth(Node node) {
if (node == null || (node.left == null && node.right == null)) {
return 0;
}
int ldepth = 1 + maxDepth(node.left);
int rdepth = 1 + maxDepth(node.right);
if (ldepth > rdepth) {
return ldepth;
} else {
return rdepth;
}
}
private int size(Node node) {
if (node == null) {
return 0;
}
return 1 + size(node.left) + size(node.right);
}
private Node insert(int data, Node node) {
if (node == null) {
node = new Node(data);
} else if (data <= node.data) {
node.left = insert(data, node.left);
} else {
node.right = insert(data, node.right);
}
//control should never reach here;
return node;
}
private boolean lookup(int data, Node node) {
if (node == null) {
return false;
}
if (node.data == data) {
return true;
}
if (data < node.data) {
return lookup(data, node.left);
} else {
return lookup(data, node.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
int treesize = 5;
bst.buildTree(treesize);
//treesize = bst.buildTreeFromOutputString("4 4 4 6 7");
treesize = bst.buildTreeFromOutputString("3 4 6 3 6");
//treesize = bst.buildTreeFromOutputString("10");
for (int i = 0; i < treesize; i++) {
System.out.println("Searching:" + i + " found:" + bst.lookup(i));
}
System.out.println("tree size:" + bst.size());
System.out.println("maxDepth :" + bst.maxDepth());
System.out.println("minvalue :" + bst.minValue());
System.out.println("maxvalue :" + bst.maxValue());
bst.printTree();
bst.printPostorder();
int pathSum = 10;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 6;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 19;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
bst.printPaths();
bst.printTree();
//bst.mirror();
System.out.println("Tree after mirror function:");
bst.printTree();
//bst.doubleTree();
System.out.println("Tree after double function:");
bst.printTree();
System.out.println("tree size:" + bst.size());
System.out.println("Same tree:" + bst.sameTree(bst));
BinarySearchTree bst2 = new BinarySearchTree();
bst2.buildTree(treesize);
treesize = bst2.buildTreeFromOutputString("3 4 6 3 6");
bst2.printTree();
System.out.println("Same tree:" + bst.sameTree(bst2));
System.out.println("---");
}
}
Now the problem is that netbeans shows Warning: Exporting a non public Type through public API for function getRoot().
I write this function to get root of tree to be used in sameTree() function, to help comparison of "this" with given tree.
Perhaps this is a OOP design issue... How should I restructure the above code that I do not get this warning and what is the concept I am missing here?
The issue here is that some code might call getRoot() but won't be able to use it's return value since you only gave package access to the Node class.
Make Node a top level class with its own file, or at least make it public
I don't really understand why you even created the getRoot() method. As long as you are inside your class you can even access private fields from any other object of the same class.
So you can change
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
to
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.root);
}
I would also add a "short path" for the case you pass the same instance to this method:
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
if (this == bst) {
return true;
}
return sameTree(this.root, bst.root);
}