So I am creating a Binary Tree through recursion, When I insert a new node I would like to jump back up to the root to start the insert from scratch again. to do that I follow this routine.
BinaryTree node = new BinaryTree();
node = this;
node = root; // this is where I want to get to
So when I coded this out and attempted to set the $this variable to root it did not set as can be seen in this picture.
Why is 'this' not set this to root? how can I jump to the top of a tree?
public void addNode(List teams, BinaryTree tree, BinaryTree root){
while(teams.size() > 1){
print(root);
//Half's the list
halfA = teams.subList(0, teams.size() / 2);
halfB = teams.subList(teams.size() / 2, teams.size());
if(parent == null){
left = new BinaryTree(halfA);
left.parent = this;
right = new BinaryTree(halfB);
right.parent = this;
}
if(countChildren(tree.left) >= countChildren(tree.right)) {
if (right == null) {
setRight(new BinaryTree(halfB));
BinaryTree temp = new BinaryTree();
parent = this;
temp = this;
temp = tree;
} else if (right != null)
right.addNode(halfB, tree, root);
}
if(countChildren(tree.right) >= countChildren(tree.left)) {
if (left == null) {
setLeft(new BinaryTree(halfA));
BinaryTree temp = new BinaryTree();
parent = this;
temp = this;
temp = tree;
} else if (left != null)
left.addNode(halfA, tree, root);
}
}
}
Related
The BST is as follows:
50 (Root 1)
/ \
40 80 (Root 2)
/ \
20 41
As you can see there are 2 root's that I am dealing with. I have tried the following code which does return the height of the tree from ROOT 1. I don't quite exactly know how to return the height from ROOT 2.
Any help on how to solve would be appreciated.
// Java program to find height of tree
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
int maxDepth(Node node)
{
if (node == null)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node.left);
int rDepth = maxDepth(node.right);
/* use the larger one */
if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}
/* Driver program to test above functions */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is : " +
tree.maxDepth(tree.root));
}
Your function for finding max depth seems like to work correctly. So fixing this issue is pretty simple.
System.out.println("Height of tree is : " +
tree.maxDepth(tree.root));
The above line prints out the height of the tree starting at the root. But if you were to start at "root 2" as you call it you would need to modify this line to start at the correct node.
System.out.println("Height of tree is : " +
tree.maxDepth(tree.root.right));
Adding an item to a Tree class should be made through a insert method.
And we can make the Node class private, it is used only by BinaryTree class.
A better data structure for a tree should be like the following, which has public insert and height methods.
public class BinaryTree {
private class Node {
private int value;
private Node left;
private Node right;
private Node(int value) {
this.value = value;
}
}
private Node root;
public void insert(int item) {
var node = new Node(item);
if (root == null) {
root = node;
return;
}
var current = root;
while (true) {
if (item < current.value) {
if (current.left == null) {
current.left = node;
break;
}
current = current.left;
} else {
if (current.right == null) {
current.right = node;
break;
}
current = current.right;
}
}
}
public int height() {
return height(root);
}
private int height(Node root) {
if (root == null)
return -1;
if (isLeaf(root))
return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
private boolean isLeaf(Node node) {
return node.left == null && node.right == null;
}
}
And to use it, just add some values, and print the height.
It is way easier to insert an item with this tree class.
BinaryTree tree = new BinaryTree();
tree.insert(50);
tree.insert(40);
tree.insert(80);
tree.insert(20);
tree.insert(41);
System.out.println(tree.height());
I had already attached two tree to test, but the answer below is weird.
Input are two trees and to check if they are inverted version. So i wrote a invert function and a BFS traverse to store the tree node into a String, through comparing the two string to check if they are inverted version.
The first tree is
5
15
14
9
6
3
1
The second tree is:
5
15
14
9
6
3
1
5
14
15
3
6
9
1
No, not mirror imagines
Process finished with exit code 0
public class CheckMirrorTree{
public static void main(String[] args) {
// add the first tree
TreeNode root = new TreeNode(5);
root.left = new TreeNode(15);
root.right = new TreeNode(14);
TreeNode rightChild = root.right;
TreeNode leftChild = root.left;
rightChild.left = new TreeNode(3);
rightChild.left.right = new TreeNode(1);
leftChild.right = new TreeNode(6);
leftChild.left = new TreeNode(9);
System.out.println("The first tree is");
String root1 = traverse(root);
// add the second tree
System.out.println("The second tree is:");
TreeNode secondRoot = new TreeNode(5);
secondRoot.right = new TreeNode(15);
secondRoot.left = new TreeNode(14);
TreeNode secondRightChild = secondRoot.right;
TreeNode secondLeftChild = secondRoot.left;
secondRightChild.left = new TreeNode(6);
secondRightChild.right = new TreeNode(9);
secondLeftChild.right = new TreeNode(3);
secondLeftChild.right.left = new TreeNode(1);
String root2 = traverse(secondRoot);
if (root1 == root2){
System.out.println("Yes, mirror images");
}else {
System.out.println("No, not mirror imagines");
}
}
static Deque<TreeNode> queue = new ArrayDeque();
static List<Integer> result = new LinkedList();
static Deque<TreeNode> invertQueue = new ArrayDeque();
static private TreeNode invertTree(TreeNode root) {
invertQueue.add(root);
TreeNode reserve = root;
while (!invertQueue.isEmpty()) {
if (root.left != null || root.right != null) {
invertQueue.poll();
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
if (root.left != null)
invertQueue.add(root.left);
if (root.right != null)
invertQueue.add(root.right);
}
root = invertQueue.poll();
}
return reserve;
}
static private String traverse (TreeNode root){ // Each child of a tree is a root of its subtree.
queue.add(root);
helper(root);
// print out the tree
String res = "";
for (int i : result) {
System.out.println(i);
res += i;
}
return res;
}
static private void helper(TreeNode root) {
while (!queue.isEmpty()) {
if(root.left != null || root.right != null) {
TreeNode temp = queue.poll();
result.add(temp.val);
if (root.left != null)
queue.add(root.left);
if (root.right != null)
queue.add(root.right);
helper(queue.peek());
}
// deal with the ending nodes
if (root.left == null && root.right == null) {
if (queue.size() == 0) {
result.add(root.val);
return;
}
result.add(queue.poll().val);
root = queue.peek();
}
}
}
}
root1 == root2
is not how you check if two strings are equal. Try:
root1.equals(root2);
Then your if statement should be entered and something will be printed.
Since nothing else is getting printed I would suggest posting the traverse method since that's probably where the program is exiting early.
I'm trying to build a binary tree recursively for an AI I'm developing.
I try to build a tree but everything comes back null. The language is Java and I'm using Eclipse. Also, I'm on a Mac if that means anything. The tree should be returned as a binary tree with nodes instantiated but without any content.
public class DecisionTree {
//build a generic, empty, tree
//building binary
Root r = new Root();
public void build() //ok
{
Node lhs = new Node();
Node rhs = new Node();
lhs = new Node();
rhs = new Node();
r.lhs = lhs;
r.rhs = rhs;
lhs.parent = r;
rhs.parent = r;
builtRecursion(lhs, 1);
builtRecursion(rhs, 1);
outputTree();
int ctr = 1; //levels of tree
}
public int builtRecursion(Node n, int ctr)
{
Node lhs = new Node();
Node rhs = new Node();
ctr++;
System.out.println("built recursion ctr is " + ctr);
if (ctr > 10)
{
//leaf node
Behaviors behavior = new Behaviors();
Node node = behavior;
n.b = behavior;
return 0;
}
n.lhs = lhs;
n.rhs = rhs;
lhs.parent = n;
rhs.parent = n;
builtRecursion(lhs, ctr);
builtRecursion(rhs, ctr);
return ctr;
}
public void outputTree()
{
if (r != null)
{
System.out.println("Root");
}
outputTreeRecursive(r);
}
public void outputTreeRecursive(Node n)
{
if (n.lhs != null)
{
System.out.println("------------------");
System.out.println("LHS");
outputTreeRecursive(n.lhs);
}
else { System.out.println("LHS is null");}
if (n.rhs != null)
{
System.out.println("-----------------");
System.out.println("RHS");
outputTreeRecursive(n.rhs);
}
else { System.out.println("RHS is null");}
System.out.println("-----------------");
}
}
ROOT CLASSS
package FLINCH;
public class Root extends Node {
Node lhs = new Node();
Node rhs = new Node();
}
NODE CLASS
package FLINCH;
import java.util.ArrayList;
import java.util.LinkedList;
public class Node {
Node lhs = null;
Node rhs = null;
Node parent = null;
Decider d = new Decider(this);
Behaviors b = null;
public LinkedList getSuccessors()
{
LinkedList list = new LinkedList();
list.add(lhs);
list.add(rhs);
return list;
}
}
OUTPUT
GetAction Running
Iterating through open list
Size of open list is 1
Peeked openLIst size is 1
Peeking throguh open list
Popping Open List
LHS is null
RHS is null
Number of children is 2
Children equals 2
Decider childrens loop
Child node is null
Iterating through children
Exception in thread "main" java.lang.NullPointerException
at FLINCH.A_Star_Search.search3(A_Star_Search.java:81)
at FLINCH.Soldier.search_behavior(Soldier.java:28)
at FLINCH.Main.getAction(Main.java:54)
at tests.GameVisualSimulationTest.main(GameVisualSimulationTest.java:52)
I hope this helps...
I have a piece of code which you can use for BinaryTree
public class BinarySearchTree {
public static Node root;
public BinarySearchTree(){
this.root = null;
}
public void insert(int id){
Node newNode = new Node(id);
if(root==null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id < current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
}
public boolean find(int id){
Node current = root;
while(current!=null){
if(current.data==id){
return true;
}else if(current.data > id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
public boolean delete(int id){
Node parent = root;
Node current = root;
boolean isLeftChild = false;
while(current.data!=id){
parent = current;
if(current.data > id){
isLeftChild = true;
current = current.left;
}else{
isLeftChild = false;
current = current.right;
}
if(current ==null){
return false;
}
}
//if i am here that means we have found the node
//Case 1: if node to be deleted has no children
if(current.left==null && current.right==null){
if(current==root){
root = null;
}
if(isLeftChild ==true){
parent.left = null;
}else{
parent.right = null;
}
}
//Case 2 : if node to be deleted has only one child
else if(current.right==null){
if(current==root){
root = current.left;
}else if(isLeftChild){
parent.left = current.left;
}else{
parent.right = current.left;
}
}
else if(current.left==null){
if(current==root){
root = current.right;
}else if(isLeftChild){
parent.left = current.right;
}else{
parent.right = current.right;
}
}else if(current.left!=null && current.right!=null){
//now we have found the minimum element in the right sub tree
Node successor = getSuccessor(current);
if(current==root){
root = successor;
}else if(isLeftChild){
parent.left = successor;
}else{
parent.right = successor;
}
successor.left = current.left;
}
return true;
}
public Node getSuccessor(Node deleleNode){
Node successsor =null;
Node successsorParent =null;
Node current = deleleNode.right;
while(current!=null){
successsorParent = successsor;
successsor = current;
current = current.left;
}
//check if successor has the right child, it cannot have left child for sure
// if it does have the right child, add it to the left of successorParent.
// successsorParent
if(successsor!=deleleNode.right){
successsorParent.left = successsor.right;
successsor.right = deleleNode.right;
}
return successsor;
}
public void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static void printInOrder(Node root){
if(root == null){
return;
}
printInOrder(root.left);
System.out.print(root.data+" ");
printInOrder(root.right);
}
public static void printPreOrder(Node root){
if(root == null){
return;
}
System.out.print(root.data+" ");
printPreOrder(root.left);
printPreOrder(root.right);
}
public static void printPostOrder(Node root){
if(root == null){
return;
}
printPostOrder(root.left);
printPostOrder(root.right);
System.out.print(root.data+" ");
}
public static void main(String arg[]){
BinarySearchTree b = new BinarySearchTree();
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("");
System.out.println("Check whether Node with value 4 exists : " + b.find(4));
System.out.println("Delete Node with no children (2) : " + b.delete(2));
b.display(root);
System.out.println("\n Delete Node with one child (4) : " + b.delete(4));
b.display(root);
System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));
b.display(root);
System.out.println();
System.out.println("********* Printing In Order *********");
printInOrder(root);
System.out.println();
System.out.println("********* Printing Pre Order *********");
printPreOrder(root);
System.out.println();
System.out.println("********* Printing Post Order *********");
printPostOrder(root);
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
when you call your buildRecursion with ctr = 1, you probably mean you want to build a tree with just one extra level and from your comment where you expect to build a leaf node, the condition needs to be modified. in your case the condition should be:
if (ctr == 1)
I made some changes to your function for better output:
public void builtRecursion(Node n, int ctr)
{
System.out.println("built recursion ctr is " + ctr);
if (ctr == 1)
{
//leaf node
Behaviors behavior = new Behaviors();
n.b = behavior;
return;
}
Node lhs = new Node();
Node rhs = new Node();
n.lhs = lhs;
n.rhs = rhs;
lhs.parent = n;
rhs.parent = n;
builtRecursion(lhs, ctr--);
builtRecursion(rhs, ctr--);
}
About the problem regarding I try to build a tree but everything comes back null, well in your outputTree and outputRecursion you don't print anything instead of "-----", "LHS", "RHS" and in case you reach where there is no left or right node you will print "LHS/RHS is null" but you should know that with a leaf node this is an accepted behavior so when you reach the leaf nodes you should print their values instead. However you can change the outputTreeRecursive to the following:
public void outputTreeRecursive(Node n)
{
if (n.lhs != null)
{
System.out.println("------------------");
System.out.println("LHS");
outputTreeRecursive(n.lhs);
}
else {
System.out.println("LHS is null");
if(n.b != null)
System.out.println("Leaf node");
}
if (n.rhs != null)
{
System.out.println("-----------------");
System.out.println("RHS");
outputTreeRecursive(n.rhs);
}
else {
System.out.println("RHS is null");
if(n.b != null)
System.out.println("Leaf node");
}
System.out.println("-----------------");
}
now probably you get better idea about your tree
I was doing an assignment in which I'm supposed to create a binary tree and define given functions from its abstract superclass (AbstractBinaryTree.java).
While working on a function called getNumbers() which is basically going to traverse through the whole tree whilst adding values from each node to an array list which it returns. There seems to be a null pointer in one of my if statements.
AbstractBinaryTree.java
import java.util.ArrayList;
public abstract class AbstractBinaryTree
{
protected Node root;
protected int sizeOfTree;
public AbstractBinaryTree()
{
root = null;
sizeOfTree = 0;
}
public int size(){ return sizeOfTree; }
/** compute the depth of a node */
public abstract int depth(Node node);
/** Check if a number is in the tree or not */
public abstract boolean find(Integer i);
/** Create a list of all the numbers in the tree. */
/* If a number appears N times in the tree then this */
/* number should appear N times in the returned list */
public abstract ArrayList<Integer> getNumbers();
/** Adds a leaf to the tree with number specifed by input. */
public abstract void addLeaf(Integer i);
/** Removes "some" leaf from the tree. */
/* If the tree is empty should return null */
public abstract Node removeLeaf();
// these methods are only needed if you wish
// use the TreeGUI visualization program
public int getheight(Node n){
if( n == null) return 0;
return 1 + Math.max(
getheight(n.getLeft()) , getheight(n.getRight())
);
}
public int height(){ return getheight(root); }
}
Node.java File.
public class Node{
protected Integer data;
protected Node left;
protected Node right;
public Node(Integer data)
{
this.data = data;
this.left = this.right = null;
}
public Node(Integer data, Node left, Node right){
this.data = data;
this.left = left;
this.right = right;
}
public Integer getData(){ return this.data; }
public Node getLeft(){ return this.left; }
public Node getRight(){ return this.right; }
public void setLeft(Node left){ this.left = left; }
public void setRight(Node right){ this.right = right; }
public void setData(Integer data){ this.data = data; }
}
BinaryTree.java
import java.util.ArrayList;
import java.util.*;
// Student Name: Adrian Robertson
// Student Number: 101020295
//
// References: Collier, R. "Lectures Notes for COMP1406C- Introduction to Computer Science II" [PDF documents]. Retrieved from cuLearn: https://www.carleton.ca/culearn/(Winter2016).//
// References: http://codereview.stackexchange.com/questions/13255/deleting-a-node-from-a-binary-search-tree
// http://www.algolist.net/Data_structures/Binary_search_tree/Removal
// http://www.geeksforgeeks.org/inorder-tree-traversal- without-recursion-and-without-stack/
public class BinaryTree extends AbstractBinaryTree
{
protected Node root = new Node(12);
public static BinaryTree create()
{
BinaryTree tempTree = new BinaryTree();
//creating all the nodes
Node temp10 = new Node(10);
Node temp40 = new Node(40);
Node temp30 = new Node(30);
Node temp29 = new Node(29);
Node temp51 = new Node(51);
Node temp61 = new Node(61);
Node temp72 = new Node(72);
Node temp31 = new Node(31);
Node temp32 = new Node(32);
Node temp42 = new Node(42);
Node temp34 = new Node(34);
Node temp2 = new Node(2);
Node temp61x2 = new Node(61);
Node temp66 = new Node(66);
Node temp3 = new Node(3);
Node temp73 = new Node(73);
Node temp74 = new Node(74);
Node temp5 = new Node(5);
//setting up the tree
if (tempTree.root.getData() == null)
{
tempTree.root.setData(12);
tempTree.root.setLeft(temp10);
tempTree.root.setRight(temp40);
}
temp10.setLeft(temp30);
temp30.setRight(temp29);
temp29.setRight(temp51);
temp51.setLeft(temp61);
temp51.setRight(temp72);
temp40.setLeft(temp31);
temp31.setLeft(temp42);
temp31.setRight(temp34);
temp34.setLeft(temp61x2);
temp61x2.setLeft(temp66);
temp61x2.setRight(temp73);
temp40.setRight(temp32);
temp32.setRight(temp2);
temp2.setLeft(temp3);
temp3.setRight(temp74);
temp74.setLeft(temp5);
return tempTree;
}
public int depth(Node node)
{
Node current = this.root;
int counter = 1;
while(node != current)
{
if (node.getData() > current.getData())
current = current.getRight();
if (node.getData() < current.getData())
current = current.getLeft();
}
return counter;
}
public boolean find(Integer i)
{
boolean found = false;
Node current = this.root;
if (i == current.getData())
found = true;
while (i != current.getData())
{
if (i > current.getData())
current = current.getRight();
if (i < current.getData())
current = current.getLeft();
if (i == current.getData())
found = true;
}
return found;
}
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current.getData() != null )
{
if (current.getLeft().getData() == null)
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre.getRight() != null && Pre.getRight() != current)
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre.getRight() == null)
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
Pre.setRight(null);
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
public void addLeaf(Integer i)
{
insert(this.root, i);
}
public static void insert(Node node, int value) //insert a node Based on provided argument where node is the root of tree
{
if (node == null)
{
Node first = new Node(value);
node = first;
}
else if (value < node.getData())
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
System.out.println(" > Inserted " + value + " to left of node " + node.getData());
Node newNode = new Node(value);
node.left = newNode;
}
}
else if (value > node.getData())
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
System.out.println(" > Inserted " + value + " to right of node " + node.getData());
Node newNode = new Node(value);
node.right = newNode;
}
}
}
public Node removeLeaf()
{
Node tempA = new Node(61); //create a new node with that value
deleteNodeBST(this.root, 61); //delete the node containing that leaf value
return tempA; //return the copy of that node
}
//delete given node with given value
public boolean deleteNodeBST(Node node, int data) {
ArrayList<Integer> temp = this.getNumbers();
if (node == null) {
return false;
}
if (node.getData() == data) {
if ((node.getLeft() == null) && (node.getRight() == null)) {
// leaf node
node = null;
return true;
}
if ((node.getLeft() != null) && (node.getRight() != null)) {
// node with two children
node.setData(temp.get(0));
return true;
}
// either left child or right child
if (node.getLeft() != null) {
this.root.setLeft(node.getLeft());
node = null;
return true;
}
if (node.getRight() != null) {
this.root.setRight(node.getRight());
node = null;
return true;
}
}
this.root = node;
if (node.getData() > data) {
return deleteNodeBST(node.getLeft(), data);
} else {
return deleteNodeBST(node.getRight(), data);
}
}
public static void main(String args[])
{
BinaryTree myTree = new BinaryTree();
myTree.create();
System.out.println(myTree.getNumbers());
}
}
The create function creates a binary tree and returns that binary tree. This is the predefined binary tree that I was supposed to create according to assignment guidelines. I understand that the tree values are not organised properly as they would be in a proper binary tree. Is that was causes the null pointer during traversal? Cause the traversal is taylored to work for a proper Binary tree.
In class BinaryTree, you initialize the left and right of your root node only if the haven't data. But the root node is create with data...
You should invert the condition in :
//setting up the tree
if (tempTree.root.getData() == null)
And add a test in getNumbers() :
if (current.getLeft() == null || current.getLeft().getData() == null)
In the BinaryTree class, getNumbers() method and while loop. Maybe your problem is here:
if (current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
When you call current.getLeft(), it will return null when the left Node is null. And then, you call getData() it will throw a NullPointerException. If you're not sure that it always not null check it before you call any methods of it. Example you can change the if statement to:
if (current.getLeft() != null && current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Or:
Node left = current.getLeft();
if (left == null) {
//TODO something here
} else if (left.getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Please update your getNumbers - method accordingly,
You need to put right checks before work with reference type.
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current != null && current.getData() != null ) // Fix here... Add : current != null
{
if (current.getLeft() != null && current.getLeft().getData() == null) // Fix here... Add : current.getLeft() != null
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre != null && Pre.getRight() != null && Pre.getRight() != current) // Fix here... Add : Pre != null
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre != null && Pre.getRight() == null) // Fix here... Add : Pre != null
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
if(Pre != null){ // Fix here... Add : Pre != null
Pre.setRight(null);
}
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
I'm trying to make a tree, in a way such that the left child of a terminal(leaf node) node.
link to see what tree should look like.
I've gotten an inorder version of the code i want, its a simple insert function that threads the tree ,but now my problem is changing this code into a preOrder insert.
This i can do, but my main problem is finding the preorder successor, which is all the way in a other sub tree, do any of you guys know a simple way to get the preorder successor?
//in-order insert
if (root == null) { // tree is empty
root = newNode;
return;
}
PreNode<T> p = root, prev = null;
while (p != null) { // find a place to insert newNode;
prev = p;
if (info.compareTo(p.info) < 0)
p = p.left;
else if (!p.hasThread) // go to the right node only if it is
p = p.right; // a descendant, not a successor;
else break; // don't follow successor link;
}
if (info.compareTo(prev.info) < 0) { // if newNode is left child of
prev.left = newNode; // its parent, the parent becomes
newNode.hasThread = true; // also its successor;
newNode.right = prev;
}
else if (prev.hasThread) { // if parent of the newNode
newNode.hasThread = true; // is not the right-most node,
prev.hasThread = false; // make parent's successor
newNode.right = prev.right; // newNode's successor,
prev.right = newNode;
}
else prev.right = newNode; // otherwise has no successor;
This will work, assuming that there is a Node class which has right&left references to its children as well as a boolean variable ht which indicates if it has a thread or not.
public void insert(T info) {
PreNode<T> newNode = new PreNode<T>(info);
if (root == null) {
root = newNode;
return;
}
PreNode<T> curr = root, r = null, l = null;
while (true) {
if (info.compareTo(curr.info) < 0) {
if (curr.right != null)
r = curr.right;
if (curr.left == null || curr.ht) {
newNode.left = r;
curr.left = newNode;
curr.ht = false;
return;
} else
curr = curr.left;
} else {
if (curr.left != null && !curr.ht)
l = curr.left;
if (curr.right == null) {
if (curr.ht) {
newNode.left = curr.left;
newNode.ht = true;
curr.left = null;
curr.right = newNode;
curr.ht = false;
return;
} else
newNode.left = r;
curr.right = newNode;
curr.ht = false;
if (l != null) {
while (!l.ht) {
if (l.right != null)
l = l.right;
else
l = l.left;
}
l.left = newNode;
l.ht = true;
return;
}
} else
curr = curr.right;
}
}
}