Java Binary Tree Main Method -
i've got class node
class node{ int val; node parent; node left; node right; public node (int val){ this.val = val; } }
and have few methods:
public class tree{ public node root = null; void insertnodesorted(node x, node tree) { if (x.val < tree.val) { if (tree.left == null) { tree.left = x; } else insertnodesorted(x, tree.left); } else { if (tree.right == null) { tree.right = x; } else insertnodesorted(x, tree.right); } } // end insertnodesorted void deletenodesorted(node x) { if (root == null) return; else root = deletenodesorted(x, root); } node deletenodesorted(node x, node tree) { if (x.val < tree.val) tree.left = deletenodesorted(x, tree.left); else if (x.val > tree.val) tree.right = deletenodesorted(x, tree.right); else tree = replacenodesorted(tree); return tree; } // end deletenodesorted // additional method node replacenodesorted(node tree) { if (tree.right == null) tree = tree.left; else if (tree.left == null) tree = tree.right; else tree.right = findreplacement(tree.right, tree); return tree; } // end replacenodesorted node findreplacement(node tree, node replace) { if (tree.left != null) tree.left = findreplacement(tree.left, replace); else { replace.val = tree.val; tree = tree.right; } return tree; } // end findreplacement
and i'd compile tree, don't know need write in main method.
public static void main(string[] args){ tree t = new tree(); t.insertnodesorted();
what have write in brackets in order print tree? (i know still have add system.out.println(val); in methods..)
you defined variable holding root
node, not necessary pass parameter tree
method insertnodesorted
. can use root
node.
add method taking 1 parameter.
public void insertnodesorted(node x) { if (root == null) { root = x; return; } insertnodesorted(x, root); }
define other method 2 parameters private
private void insertnodesorted(node x, node tree) { ... }
now can insert elements follow:
tree t = new tree(); t.insertnodesorted(new node(1)); t.insertnodesorted(new node(134)); t.insertnodesorted(new node(13)); t.insertnodesorted(new node(4)); ...
Comments
Post a Comment