Extended version of Binary tree
A node can be binary. Two children. Left and Right.
Example:
A
B C
class Node
public int data; // data item (key)
public Node leftChild;
public Node rightChild; But how would I create a tree with the node can contain as much children?
A
B C R T
and so on? I want to insert a node in A and have it expand each time. Node "A" will contain node {B,C,R,T} for example.
How would I code this?
Much depends on how you see the relation between a Node and it's children. In the simplest form you could just change
class Node
public int data; // data item (key)
public Node leftChild;
public Node rightChild; to
class Node
public int data;
public Node[] children;
}or
class Node
public int data;
public ArrayList children;
}BUT
what you probably want is for the ordering to be equivalent to
class Node
public Node leftChild;
public int data; // data item (key)
public Node rightChild;
} i.e. the data of the current node is sandwiched between that of the left and right nodes.
A BTree is one of the best examples of this (Google is your friend). An approach (and I stress AN) is to have an array of say 'n' values and an array of 'n+1' child nodes with the implied sandwich ordering
[child 0][data0][child 1][data 1] ... [child n][data n][child n+1].
The result is then
class Node
int[] data = ...;
Node[] childrean = ...
}where you would dynamically size the 'data' and 'children' arrays and the length of 'children' is always 1 greater than the order of 'data'.
Similar Messages
-
How to extend breadth first Search for Binary Tree to any kind of Tree??
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
I have following code to successfully apply for breadth first Search in Binary Tree as follows,
package a.border;
import java.util.ArrayList;
import java.util.LinkedList;
public class Tree
int root;
Tree left;
Tree right;
static ArrayList<Integer> list = new ArrayList<Integer>();
static ArrayList<Tree> treeList = new ArrayList<Tree>();
private static LinkedList<Tree> queue = new LinkedList<Tree>();
* @param root root value
* @param left left node
* @param right right node
public Tree(int root, Tree left, Tree right)
this.root = root;
this.left = left;
this.right = right;
/** Creates a new instance of Tree
* You really should know what this does...
* @param root
public Tree(int root)
this.root = root;
this.left = null;
this.right = null;
* Simply runs a basic left then right traversal.
public void basicTraversal()
//Check if we can go left
if (left != null)
left.basicTraversal();
//Add the root
list.add(root);
//Check if we can go right
if (right != null)
right.basicTraversal();
public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
//Add the root to the arraylist, we know it is always the first entry.
list.add(root);
//Basically we add the first set of nodes into the queue for
//traversing.
//Query if left exists
if (left != null)
//Then add the node into the tree for traversing later
queue.add(left);
//Same for right
if (right != null)
queue.add(right);
//Then we call the traverse method to do the rest of the work
return traverse(list);
private ArrayList<Integer> traverse(ArrayList<Integer> list)
//Keep traversing until we run out of people
while (!queue.isEmpty())
Tree p = queue.remove();
//Check if it has any subnodes
if (p.left != null)
//Add the subnode to the back of the queue
queue.add(p.left);
//Same for left
if (p.right != null)
//Same here, no queue jumping!
queue.add(p.right);
//Append to the ArrayList
list.add(p.root);
//And return
return list;
* Makes a tree and runs some operations
* @param args
public static void main(String[] args)
* 4
* t = 2 6
* 1 3 5 7
Tree leaf6 = new Tree(1);
Tree leaf7 = new Tree(3);
Tree leaf8 = new Tree(5);
Tree leaf9 = new Tree(7);
Tree t4 = new Tree(2, leaf6, leaf7);
Tree t5 = new Tree(6, leaf8, leaf9);
Tree t = new Tree(4, t4, t5);
t.basicTraversal();
System.out.println("Here is basicTraversal ="+list.toString());
list.clear();
t.getBreadthTraversal(list);
System.out.println("getBreadthTraversal= " +list.toString());
list.clear();
}Can Guru help how to update to any kind of tree??
here this code is for the tree like:
* 4
* t = 2 6
* 1 3 5 7
*/But i hope the new code can handle tree like:
* 4
* / | \
* / | \
* t = 2 8 6
* / | \ | /| \
* 1 11 3 9 5 10 7
*/Thankssunnymanman wrote:
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
What do all trees have in common? And what do all nodes in trees have in common?
At least these things:
interface Tree<T> {
Node<T> getRoot();
interface Node<T> {
T getData();
List<Node<T>> getChildren();
}Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
class BinaryTree<T extends Comparable<T>> implements Tree<T> {
protected BTNode<T> root;
public Node<T> getRoot() {
return root;
class BTNode<T> implements Node<T> {
private T data;
private Node<T> left, right;
public List<Node<T>> getChildren() {
List<Node<T>> children = new ArrayList<Node<T>>();
children.add(left);
children.add(right);
return children;
public T getData() {
return data;
class NTree<T> implements Tree<T> {
private NTNode<T> root;
public Node<T> getRoot() {
return root;
class NTNode<T> implements Node<T> {
private T data;
private List<Node<T>> children;
public List<Node<T>> getChildren() {
return children;
public T getData() {
return data;
}Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
interface Traverser<T> {
List<Node<T>> traverse(T goal, Tree<T> tree);
}And finally write an implementation for it:
class BreathFirst<T> implements Traverser<T> {
public List<Node<T>> traverse(T goal, Tree<T> tree) {
Node<T> start = tree.getRoot();
List<Node<T>> children = start.getChildren();
// your algorithm here
return null; // return your traversal
}... which can be used to traverse any tree! Here's a small demo of how to use it:
public class Test {
public static void main(String[] args) {
Tree<Integer> binTree = new BinaryTree<Integer>();
// populate your binTree
Tree<Integer> nTree = new NTree<Integer>();
// populate your nTree
Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
// Look for integer 6 in binTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
// Look for integer 6 in nTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
}Good luck! -
So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
I am sorry for such sloppy code.. I have been changing and rearranging too much.
import java.io.*;
import java.util.*;
public class MorseCode extends BinaryTree{
static BufferedReader in;
static BinaryTree<String> bT = new BinaryTree<String>();
/* public static void loadTree() throws FileNotFoundException, IOException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
public static String decode(Character c) throws IOException{
if(c.equals("null")){
return "";
}else if(c.equals(" ")){
return " ";
}else{
return (":" + find(c));
public static String find(Character c) throws IOException, FileNotFoundException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
Queue<BinaryTree> data = new LinkedList<BinaryTree>();
BinaryTree<String> tempTree = bT;
String temp = null;
Character tempChar = null;
data.offer(tempTree);
while(!data.isEmpty()){
tempTree = data.poll();
temp = tempTree.getData();
tempChar = temp.charAt(0);
if(tempChar.equals(c)){
break;
data.offer(tempTree.getRightSubtree());
data.offer(tempTree.getLeftSubtree());
return temp.substring(2);
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner scan = new Scanner(new FileReader("encode.in.txt"));
String s = "";
String temp = "";
while(scan.hasNextLine()){
temp = scan.nextLine();
for(int i = 0; i < temp.length(); i++){
s = s + decode(temp.charAt(i));
System.out.println(s);
/** Class for a binary tree that stores type E objects.
* @author Koffman and Wolfgang
class BinaryTree <E> implements Serializable
//===================================================
/** Class to encapsulate a tree node. */
protected static class Node <E> implements Serializable
// Data Fields
/** The information stored in this node. */
protected E data;
/** Reference to the left child. */
protected Node <E> left;
/** Reference to the right child. */
protected Node <E> right;
// Constructors
/** Construct a node with given data and no children.
@param data The data to store in this node
public Node(E data) {
this.data = data;
left = null;
right = null;
// Methods
/** Return a string representation of the node.
@return A string representation of the data fields
public String toString() {
return data.toString();
}//end inner class Node
//===================================================
// Data Field
/** The root of the binary tree */
protected Node <E> root;
public BinaryTree()
root = null;
protected BinaryTree(Node <E> root)
this.root = root;
/** Constructs a new binary tree with data in its root,leftTree
as its left subtree and rightTree as its right subtree.
public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
root = new Node <E> (data);
if (leftTree != null) {
root.left = leftTree.root;
else {
root.left = null;
if (rightTree != null) {
root.right = rightTree.root;
else {
root.right = null;
/** Return the left subtree.
@return The left subtree or null if either the root or
the left subtree is null
public BinaryTree <E> getLeftSubtree() {
if (root != null && root.left != null) {
return new BinaryTree <E> (root.left);
else {
return null;
/** Return the right sub-tree
@return the right sub-tree or
null if either the root or the
right subtree is null.
public BinaryTree<E> getRightSubtree() {
if (root != null && root.right != null) {
return new BinaryTree<E>(root.right);
} else {
return null;
public String getData(){
if(root.data == null){
return "null";
}else{
return (String) root.data;
/** Determine whether this tree is a leaf.
@return true if the root has no children
public boolean isLeaf() {
return (root.left == null && root.right == null);
public String toString() {
StringBuilder sb = new StringBuilder();
preOrderTraverse(root, 1, sb);
return sb.toString();
/** Perform a preorder traversal.
@param node The local root
@param depth The depth
@param sb The string buffer to save the output
private void preOrderTraverse(Node <E> node, int depth,
StringBuilder sb) {
for (int i = 1; i < depth; i++) {
sb.append(" ");
if (node == null) {
sb.append("null\n");
else {
sb.append(node.toString());
sb.append("\n");
preOrderTraverse(node.left, depth + 1, sb);
preOrderTraverse(node.right, depth + 1, sb);
/** Method to read a binary tree.
pre: The input consists of a preorder traversal
of the binary tree. The line "null" indicates a null tree.
@param bR The input file
@return The binary tree
@throws IOException If there is an input error
public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
// Read a line and trim leading and trailing spaces.
String data = bR.readLine().trim();
if (data.equals("null")) {
return null;
else {
BinaryTree < String > leftTree = readBinaryTree(bR);
BinaryTree < String > rightTree = readBinaryTree(bR);
return new BinaryTree < String > (data, leftTree, rightTree);
}//readBinaryTree()
/*Method to determine the height of a binary tree
pre: The line "null" indicates a null tree.
@param T The binary tree
@return The height as integer
public static int height(BinaryTree T){
if(T == null){
return 0;
}else{
return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
public static String preOrderTraversal(BinaryTree<String> T){
String s = T.toString();
String s2 = "";
String temp = "";
Scanner scan = new Scanner(s);
while(scan.hasNextLine()){
temp = scan.nextLine().trim();
if(temp.equals("null")){
s2 = s2;
}else{
s2 = s2 + " " + temp;
return s2;
}//class BinaryTreeAs well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
public static void main(String[] args) throws FileNotFoundException, IOException{
//Scanner scan = new Scanner(new FileReader("encode.in.txt"));
Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
public static String decode(Character c) throws IOException{
if(c.equals("null")){
c is a Character so it will never be the case that it is equal to the string n-u-l-l.
Perhaps the behaviour of each of these methods needs to be (documented and) tested. -
How to crossover this binary tree..?
You can view detail http://www.codeguru.com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
[nha khoa|http://www.sieuthi77.com/main/nhakhoa.html] .com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
I have these classes which model a tree (binary). the thing is i cant figure out how i can set the elements of individual nodes in that tree. i can get individual elements but i cannot set them due to the strucutre of the tree and how it is implemented. The changes that I make to these classes should be as less as possible, because i have an algorithm which generates the tree structure randomly, plus i can evaluate the tree easily by using recursion. The only left thing to do is CROSSOVER but how?!?
here are the classes which model my binary tree:
Code:
public abstract class Node implements Cloneable{
abstract double evaluate(VariableInput v);
abstract String print();
abstract int getNumberOfNodes();
abstract ArrayList<Object> getChildren();
@Override
public Node clone(){
Node copy;
try {
copy = (Node) super.clone();
} catch (CloneNotSupportedException unexpected) {
throw new AssertionError(unexpected);
//In an actual implementation of this pattern you might now change references to
//the expensive to produce parts from the copies that are held inside the prototype.
return copy;
Code:
public class UnaryNode extends Node {
private UnaryFunction operator;
private Node left;
public UnaryNode(UnaryFunction op, Node terminal) {
operator = op;
this.left = terminal;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + ")";
return r;
void setLeft(Node left) {
this.left = left;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes();
Node getLeft() {
return left;
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
return arr;
Code:
public class BinaryNode extends Node {
private BinaryFunction operator;
private Node left;
private Node right;
public BinaryNode(BinaryFunction op, Node left, Node right) {
operator = op;
this.left = left;
this.right = right;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + " " + right.print()+")";
return r;
public void setLeft(Node left){
this.left = left;
public void setRight(Node right){
this.right = right;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes() + right.getNumberOfNodes();
Node getRight() {
return right;
Node getLeft() {
return left;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
arr.addAll(right.getChildren());
return arr;
public class NumericNode extends Node{
private double value;
public NumericNode(double v){
value = v;
@Override
double evaluate(VariableInput c) {
return value;
public String print(){
String r = "" + value;
return r;
@Override
int getNumberOfNodes() {
return 1;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(new NumericNode(value));
return arr;
}p.s. I have this get children method which return a list of REFERENCES to all the nodes in the tree, but if i change any of them it wont have an effect to the tree itself because they are references.
Any ideas or codes will be much appreciated. Thanks!What? Changes to what a node is referencing will be reflected in the tree, unless your getChildren is returning a copy, like in NumericNode.
Kaj -
Bonjour, quand j'utilise mon adobe photoshop cs6 extended (Version Adobe Photoshop : 13.0.6 (13.0.6 20131025.r.54 2013/10/25:21:00:00) x64) notamment avec les calques, le clavier de mon Mac Book Pro ( osx 10,9,5 - 2,64 GHZ intel core i7 -8GO 1333 MHTZ ) se bloque. Je suis obligé d'enregistrer ce que je fais dans le texte pré inscrit, puis de rouvrir pour enregistrer dans la rubrique et dans les termes voulu.
Merci de m'indiquer comment résoudre ce problème.Bonjour! Oui: il faudrait essayer de réinitialiser les préférences, en maintenant CTRL+SHIFT+ALT dès que l'on démarre Photoshop, ce qui supprime le fichier des préférence et le remplace par un nouveau. On doit alors obtenir un message qui demande si on veut recréer les préférences.
La réinstallation ne remplace pas ce fichier, et c'est lui qui peut être corrompu lors d'un arret fatal de la machine.
On peut le remplacer manuellement, en suivant les instructions de ce document remplacer évidemment CS5 par CS6: http://helpx.adobe.com/fr/photoshop/kb/preference-file-functions-names-locations.html
Les pilotes des cartes graphiques datent de Janvier. Y-a-t-il des mises à jour disponibles?
De même, Photoshop n'est pas dans sa version 13.0.1.1 il convient de se rendre dans Aide>Mises à Jour -
Ok, I am making a binary tree. I have a question for my insert method. Firstly, I can't find out why the root node is inserted more than once in the tree. Also, I am having trouble with connecting the nodes that I insert to the tree. I can attach modes to root just fine, but I can't find out how to attach nodes to the existing nodes that are already attached to the tree. When I insert a node that meets the criteria of an already existing node, it replaces the node instead of getting attached to it. The answer is probably trivial, but I can't find it. Here is my insert method.
public void insert(T obj) {
int _result1;
int _result2;
//TODO: Implement Q1 here
if(isEmpty() == true){
_root = createNode(obj, null, null, null);
System.out.println("The root inserted is " + _root.element());
insert(obj);
_node = createNode(obj, _root, null, null);
_result1 = _node.element().compareTo(_root.element());
if(_result1 < 0){
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _node2.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " + _current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasLeft() == true){
_node1.getLeft();
_current = _node1.getLeft();
else{
_current.setLeft(_node1);
_current = _node2;
else{
_node1 = createNode(obj, _node, null, null);
_node.setLeft(_node1);
_node1.setParent(_node);
System.out.println("The parent of the left node " + _node.element() + " is " + _node.getParent().element());
_root.setLeft(_node1);
_current = _node1;
//System.out.println("The current element is " + _node.element());
else{
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _current.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " +_current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasRight() == true){
_node1.getRight();
_current = _node1.getRight();
else{
_current.setLeft(_node1);
_current = _node1;
else{
_node1 = createNode(obj, _node, null, null);
_node.setRight(_node1);
_node1.setParent(_node);
//_current = _node1;
System.out.println("The parent of the right node " + _node.element() + " is " + _node.getParent().element());
_root.setRight(_node1);
_current = _node1;
//System.out.println("The current element is " + _current.element());
}The output I get is:
The root inserted is 6
The parent of the right node 6 is 6
The parent of the right node 6 is 6 ** I can't figure out why the root is inserted two extra times**
The parent of the left node 3 is 6
The parent of the right node 11 is 6
The parent of the right node 12 is 6 ** this node should be attaching to 11 instead of replacing it **
The parent of the right node 8 is 6
The parent of the right node 9 is 6
The parent of the right node 10 is 6
The parent of the right node 7 is 6
preorder :(6 (3 )(7 ))
postorder:(( 3) ( 7) 6)IMO, your insert method is way too complicated.
Have a look at this pseudo code: that's all it takes to insert nodes in a BT:
class Tree<T extends Comparable<T>> {
private Node root;
public void insert(T obj) {
'newNode' <- a new Node('obj') instance
IF 'root' equals null
let 'root' be the 'newNode'
ELSE
insert('root', 'newNode')
END IF
public void insert(Node parent, Node newNode) {
IF 'parent' is less than 'newNode'
IF the left child of 'parent' is null
let 'newNode' be the left child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
ELSE
IF the right child of 'parent' is null
let 'newNode' be the right child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
END IF
} -
How to Pretty Print a Binary Tree?
I'm trying to display a Binary Tree in such a way:
________26
___13_________2
1_______4 3_________1
(without the underscores)
however I cannot figure out the display method.
class BinaryNode
//Constructors
BinaryNode leftChild, rightChild;
Object data;
BinaryNode()
leftChild = null;
data = null;
rightChild = null;
BinaryNode( Object d, BinaryNode left, BinaryNode right)
leftChild = left;
data = d;
rightChild = right;
//Height
public static int Height(BinaryNode root)
if (root == null)
return 0;
if ((Height(root.leftChild)) > Height(root.rightChild))
return 1 + Height(root.leftChild);
return 1 + Height(root.rightChild);
//Count
public static int Count(BinaryNode root)
if(root==null)
return 0;
return 1 + Count(root.leftChild) + Count(root.rightChild);
//Display
public static void Display(BinaryNode root)
int level = 2^(Level(root)-1)
for (int i = 1; i<Height(root)+1; i++)
System.out.printf("%-4s%
Display(root, i);
System.out.println();
public static void Display(BinaryNode root, int level)
if (root!=null)
if(level==1)
System.out.print(root.data + " ");
else
Display(root.leftChild, level-1);
Display(root.rightChild, level-1);
//Level
public static int Level(BinaryNode root)
if(root==null)
return 0;
if(root.leftChild == null && root.rightChild == null)
return 1;
return Level(root.leftChild) + Level(root.rightChild);
Edited by: 815035 on Nov 23, 2010 12:27 PMThe example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
Unfortunately it is also quite difficult to accomplish using System.out.print statements.
You have to print out the root of the tree first (its at the top)
However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
So you will need to traverse the tree at least twice.
Once to work out the offsets, and again to print out the values.
The working out of offsets would have to be a depth search traversal I think
The printing of the values in this fashion would be a breadth first traversal.
I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
ie the root was on the left, the leaves of the tree on the right of the screen.
That meant you could do an inorder depth traversal of the tree to just print it once.
hope this helps,
evnafets -
Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
public Object clone()
DigitalTree<E> treeClone = null;
try
treeClone = (DigitalTree<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
cloneNodes(treeClone, this.root, treeClone.root);
return treeClone;
private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
if(treeClone.size == 0)
cloneNode = null;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
else if(currentNode != null)
cloneNode = (Node<E>)currentNode.clone();
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
}In the Node class:
public Object clone()
Node<E> nodeClone = null;
try
nodeClone = (Node<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
return nodeClone;
}Hello jssutton
Your question inspired me to try my own binary tree and cloning. My cloning algorithm is similar to yours but with one difference.
In my class Tree defined as:
class Tree<T extends Comparable>
I have:
private void deepCopyLeft(TreeNode<T> src, TreeNode<T> dest) {
if (src == null) return;
dest.mLeft = new TreeNode<T>(src.mValue);
deepCopyLeft(src.mLeft, dest.mLeft);
deepCopyRight(src.mRight, dest.mLeft);
private void deepCopyRight(TreeNode<T> src, TreeNode<T> dest) {
if (src == null) return;
dest.mRight = new TreeNode<T>(src.mValue);
deepCopyLeft(src.mLeft, dest.mRight);
deepCopyRight(src.mRight, dest.mRight);
public Tree<T> deepCopy() {
if (root == null) return new Tree<T>();
TreeNode<T> newRoot = new TreeNode<T>(root.mValue);
deepCopyLeft(root.mLeft, newRoot);
deepCopyRight(root.mRight, newRoot);
return new Tree<T>(newRoot);
}Its a similar recursive idea, but with 2 extra functions. I hope that helps. I don't have time right now to pinpoint the problem in your routine. Good luck. -
Writting Methods of Binary Tree
I am using java code to write some binary tree methods.
Got stuck in some of the following methods.
Hopefully i can get some help here.
Public int width(){
// Return the maximun number of nodes in each level
Public boolean checkIsFullTree(){
// Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full)
Public boolean checkIsCompleteTree(){
// Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full and is filled from left to right)
at last
Public int internalPathLength(){
// Return The sum of all internal nodes of the paths from the root of an extended binary tree to each node.
other words, the sum of all depths of nodes.
Looking forawad to see some replies. ChreesI have came up with some ideas.
Public boolean checkIsFullTree(TreeNode t, int currentHeight ) {
int maxHeight = height(); // Maximum height.
int currentHeight=currentHeight;
if (t == null){
return false;
if (t.left() ! = null){
currentHeight++;
checkIsFullTree(t.left(), currentHeight);
if (t.right() ! = null){
currentHeight++;
checkIsFullTree(t.right(), currentHeight);
if ( t.left() == null && t.right() == null){
if (currentHeight == maxHeight) {
check = true;
}else{
check = false;
But i am missing sometime here i guess.
} -
I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
public class BTNode {
private customer item;
private BTNode left;
private BTNode right;
public BTNode() {// constructor
item = null;
left = right = null;
public BTNode(customer newItem) {// constructor
item = newItem.clone();
left = right = null;
public void setItem(customer newItem) {// set methods
item = newItem.clone();
public void setLeft(BTNode newLeft) {
left = newLeft;
public void setRight(BTNode newRight) {
right = newRight;
public customer getItem() { // get methods
return item;
public BTNode getLeft() {
return left;
public BTNode getRight() {
return right;
public class Queue1 extends BTNode {
public Queue1() {
super();
public void enqueue(BTNode newItem) {
public void dequeue() {
}public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
You probably want to aggregate a List.
Kaj -
Is it possible to upgrade from CS6 Extended version 13.0 x64 to the latest version?
Is it possible to upgrade from CS6 Extended version 13.0 x64 to the latest version?
There are three current version of CS6 perpetual versions Mac version 13.0.6 and Windows Version version 13.0.1.3 and there is a creative cloud sibscruption version 13.1.2.
If you running Windows on a 64Bit system and install Perpetual CS6 it would have installed at version 13.0.0 and the be updated to version 13.0.1.3. Both a 32 bit version and a 64 bit version of Photoshop would have been installed on your windows system. The 32 bit version will be in your windows "Program Files (x86)" tree anf the 64 bit version in the "Program Files" tree there should be two startup icon in the start button for starting CS6.
There would also be a 32 bit and 64 bit windows subscription version installed on windows.
Mac CS6 is 64bit only. -
Need Help with a String Binary Tree
Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
plssss... someone pls help me on this
here is my code now:
// TreeApp.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*; // for I/O
import java.util.*; // for Stack class
import java.lang.Integer; // for parseInt()
class Node
//public int iData; // data item (key)
public String iData;
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
} // end class Node
class Tree
private Node root; // first node of tree
public Tree() // constructor
{ root = null; } // no nodes in tree yet
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
return current; // found it
} // end find()
public Node recfind(int key, Node cur)
if (cur == null) return null;
else if (key < cur.iData) return(recfind(key, cur.leftChild));
else if (key > cur.iData) return (recfind(key, cur.rightChild));
else return(cur);
public Node find2(int key)
return recfind(key, root);
public void insert(int id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public void insert(String id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
//if(id < current.iData) // go left?
if(id.compareTo(current.iData)>0)
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public Node betterinsert(int id, double dd)
// No duplicates allowed
Node return_val = null;
if(root==null) { // no node in root
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
root = newNode;
return_val = root;
else // root occupied
Node current = root; // start at root
Node parent;
while(current != null)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.leftChild = newNode;
} // end if go left
else if (id > current.iData) // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.rightChild = newNode;
} // end else go right
else current = null; // duplicate found
} // end while
} // end else not root
return return_val;
} // end insert()
public boolean delete(int key) // delete node with given key
if (root == null) return false;
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while(current.iData != key) // search for node
parent = current;
if(key < current.iData) // go left?
isLeftChild = true;
current = current.leftChild;
else // or go right?
isLeftChild = false;
current = current.rightChild;
if(current == null)
return false; // didn't find it
} // end while
// found node to delete
// if no children, simply delete it
if(current.leftChild==null &&
current.rightChild==null)
if(current == root) // if root,
root = null; // tree is empty
else if(isLeftChild)
parent.leftChild = null; // disconnect
else // from parent
parent.rightChild = null;
// if no right child, replace with left subtree
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
// if no left child, replace with right subtree
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;
else // two children, so replace with inorder successor
// get successor of node to delete (current)
Node successor = getSuccessor(current);
// connect parent of current to successor instead
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// connect successor to current's left child
successor.leftChild = current.leftChild;
// successor.rightChild = current.rightChild; done in getSucessor
} // end else two children
return true;
} // end delete()
// returns node with next-highest value after delNode
// goes to right child, then right child's left descendents
private Node getSuccessor(Node delNode)
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; // go to right child
while(current != null) // until no more
{ // left children,
successorParent = successor;
successor = current;
current = current.leftChild; // go to left child
// if successor not
if(successor != delNode.rightChild) // right child,
{ // make connections
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
return successor;
public void traverse(int traverseType)
switch(traverseType)
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
System.out.println();
private void preOrder(Node localRoot)
if(localRoot != null)
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
private void inOrder(Node localRoot)
if(localRoot != null)
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
private void postOrder(Node localRoot)
if(localRoot != null)
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
public void displayTree()
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
while(isRowEmpty==false)
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
Node temp = (Node)globalStack.pop();
if(temp != null)
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
else
System.out.print("--");
localStack.push(null);
localStack.push(null);
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
} // end displayTree()
} // end class Tree
class TreeApp
public static void main(String[] args) throws IOException
int value;
double val1;
String Line,Term;
BufferedReader input;
input = new BufferedReader (new FileReader ("one.txt"));
Tree theTree = new Tree();
val1=0.1;
while ((Line = input.readLine()) != null)
Term=Line;
//val1=Integer.parseInt{Term};
val1=val1+1;
//theTree.insert(Line, val1+0.1);
val1++;
System.out.println(Line);
System.out.println(val1);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
while(true)
putText("Enter first letter of ");
putText("show, insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
case 's':
theTree.displayTree();
break;
case 'i':
putText("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
putText("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
putText("Found: ");
found.displayNode();
putText("\n");
else
putText("Could not find " + value + '\n');
break;
case 'd':
putText("Enter value to delete: ");
value = getInt();
boolean didDelete = theTree.delete(value);
if(didDelete)
putText("Deleted " + value + '\n');
else
putText("Could not delete " + value + '\n');
break;
case 't':
putText("Enter type 1, 2 or 3: ");
value = getInt();
theTree.traverse(value);
break;
default:
putText("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static void putText(String s)
System.out.print(s);
System.out.flush();
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class TreeAppString str = "Hello";
int index = 0, len = 0;
len = str.length();
while(index < len) {
System.out.println(str.charAt(index));
index++;
} -
Adobe Acrobat 9 Pro Extended, Version 9.5.0, crashes when printing
Hello,
Adobe Acrobat 9 Pro Extended, Version 9.5.0, crashes when printing:
Problemsignatur:
Problemereignisname: APPCRASH
Anwendungsname: Acrobat.exe
Anwendungsversion: 9.5.0.270
Anwendungszeitstempel: 4f03f71d
Fehlermodulname: Acrobat.dll
Fehlermodulversion: 9.5.0.270
Fehlermodulzeitstempel: 4f03f251
Ausnahmecode: c0000005
Ausnahmeoffset: 006ccadd
Betriebsystemversion: 6.1.7601.2.1.0.256.1
Gebietsschema-ID: 1031
Zusatzinformation 1: 0a9e
Zusatzinformation 2: 0a9e372d3b4ad19135b953a78882e789
Zusatzinformation 3: 0a9e
Zusatzinformation 4: 0a9e372d3b4ad19135b953a78882e789
Thank you very much for your help.I do have the same problem but I'm OSX 10.6.8
I have a Phaser 7500, and it works fine with ID, PS, AI, and Acrobat Reader 9.5
But crashes with Acrobat Pro 9.5 and Lightroom 3.6
Latest drivers for the Phaser in installed, tried the Repais Acrobat Installation but
it' says it isn't necesary
Process: AdobeAcrobat [6142]
Path: /Applications/Adobe Acrobat 9 Pro/Adobe Acrobat Pro.app/Contents/MacOS/AdobeAcrobat
Identifier: com.adobe.Acrobat.Pro
Version: 9.5.0 (9.5.0)
Code Type: X86 (Native)
Parent Process: launchd [178]
Date/Time: 2012-01-23 17:35:51.285 +0100
OS Version: Mac OS X 10.6.8 (10K549)
Report Version: 6
Interval Since Last Report: 573578 sec
Per-App Interval Since Last Report: 318700 sec
Per-App Crashes Since Last Report: 1
Anonymous UUID: 2FBD03A6-9A6E-407D-B683-2DA98F1D700F
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000030000000
Crashed Thread: 0 Dispatch queue: com.apple.main-thread -
PDF fillable form saved as reader extended version will not open in reader on ipad2
I have forms that I have created in livecycle and saved as reader extended versions. We I try to open them from adobe.com in the adobe reader on my ipad2 I get the Please wait... screen the form never opens. Any help?
Technically, they can be opened but we will only display the placeholder page asking you to "wait" =). The form content is not viewable or fillable.
-
A Binary Tree Implementation in ABAP
Hi,
Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
Thanks,
Manjula.Hi manjula,
This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It.
It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing through the tree.
For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
*& Report YBINTREE - Build/Print Binary Tree of numbers *
report ybintree .
types: begin of stree,
value type i,
left type ref to data,
right type ref to data,
end of stree.
data: tree type stree.
data: int type i.
data: begin of rnd occurs 0,
num type i,
end of rnd.
start-of-selection.
do 100 times.
generate random number between 0 and 100
call function 'RANDOM_I4'
exporting
rnd_min = 0
rnd_max = 100
importing
rnd_value = int.
store numbers
rnd-num = int.
append rnd.
build binary tree of random numbers
perform add_value using tree int.
enddo.
stored numbers are sorted for comparison
sort rnd by num.
print sorted random numbers
write: / 'Sorted Numbers'.
write: / '=============='.
skip.
loop at rnd.
write: rnd-num.
endloop.
skip.
print binary tree. This should give the same result
as the one listed from the internal table
write: / 'Binary Tree List'.
write: / '================'.
skip.
perform print_value using tree.
skip.
*& Form add_value
text - Build tree with value provided
-->TREE text
-->VAL text
form add_value using tree type stree val type i.
field-symbols: <ltree> type any.
data: work type stree.
if tree is initial. "When node has no values
tree-value = val. " assign value
clear: tree-left, tree-right.
create data tree-left type stree. "Create an empty node for left
create data tree-right type stree. "create an empty node for right
else.
if val le tree-value. "if number is less than or equal
assign tree-left->* to <ltree>. "assign the left node to fs
call add_value recursively with left node
perform add_value using <ltree> val.
else. "if number is greater
assign tree-right->* to <ltree>. "assign the right node to fs
call add_value recursively with right node
perform add_value using <ltree> val.
endif.
endif.
endform. "add_value
*& Form print_value
text - traverse tree from left-mid-right order
automatically this will be sorted list
-->TREE text
form print_value using tree type stree.
field-symbols: <ltree> type any.
if tree is initial. "node is empty
else. "non-empty node
assign tree-left->* to <ltree>. "left node
perform print_value using <ltree>. "print left
write: tree-value. "print the current value
assign tree-right->* to <ltree>. "right node
perform print_value using <ltree>. "print right
endif.
endform. "print_value
pls reward if helps,
regards.
Maybe you are looking for
-
Null/Empty Strings use in ESB Database Adapter
Hi I'm trying to use a database adapter to execute an update on a table with a composite primary key; one of the primary key columns sometimes contains an empty string, however whenever I try to call the adapter, it always converts this to a null val
-
The continually updating 5g iPod (1.2)/ iTunes7
I recently updated to iTunes 7 and firmware 1.2. Now when I connect the iPod, it updates it just fine and then it disconnects it at the end of the sync. That's all fine, I just want it to sit there and charge. But, after about 3 seconds of being disc
-
How to get uneven distribution of blended lines
Is there a way to achieve uneven distrubution of blended lines in Illustrator CS5? There was one other post on the web asking a similar question to this, which was solved by changing the blend spline. This works great for objects, but not so much for
-
Trial download "The serial number you entered is not valid" ?
Hi I have just downloaded the trial version of the new aperture software but when I try to enter the serial number (Copy and pasted from the email) it says the serial number is not valid. Any ideas? I do not have any previous versions on my macbook a
-
NAC L3 OOB - Online Users not correct
I'm testing a NAC 4.1.3 L3 OOB Real IP configuration and have come across an anomaly. Can someone help please. I have configured two switches to be managed by NAC and have configured a role for Web Authentication and set all ports to be controlled. W