Java: binary tree recursion methods -
i'm quite new java , 1 of our assignments requires me create binary tree containing nodes int values. professor wants use 1 class containing main method. applied 2 recursive methods, 1 insert node , 1 display existing nodes. whenever run code however, console displays recent node entered. there wrong methods used? have far:
import java.util.scanner; public class node { private int value; static node root; public node leftlink; public node rightlink; public node(int v) { this.value = v; } public int getvalue() { return value; } static void traverseshow() { if(root.leftlink != null){ root = root.leftlink; traverseshow(); } system.out.println(root.getvalue()); if(root.rightlink != null) { root = root.rightlink; traverseshow(); } return; } static void addnode(node n) { if(root==null) { root = n; } else { if(root.getvalue()>n.getvalue()) { root = root.leftlink; addnode(n); } if(root.getvalue()<n.getvalue()) { root = root.rightlink; addnode(n); } } return; } public static void main(string[] args) { int val = 0; scanner sc = new scanner(system.in); boolean loop = true; string command = ""; while(loop==true) { system.out.println("please enter command:"); system.out.println("a = insert new value"); system.out.println("b = display values"); system.out.println("c = exit program"); command = sc.next(); if(command.equalsignorecase("a")) { system.out.println("enter value: "); val = sc.nextint(); node newnode = new node(val); addnode(newnode); } else if(command.equalsignorecase("b")) { traverseshow(); } else if(command.equalsignorecase("c")) { sc.close(); system.exit(0); } else { system.out.println("invalid command! please try again."); } } } }
you're setting root new node when you're traversing tree find put new node. 1 simple option store current root in temporary variable , put after insert node.
static void addnode(node n) { if(root==null) { root = n; } else { node tmp = root; // save current root if(root.getvalue()>n.getvalue()) { root = root.leftlink; addnode(n); } else if(root.getvalue()<n.getvalue()) { root = root.rightlink; addnode(n); } root = tmp; // put root original value } return; }
you should similar traverseshow method well.
Comments
Post a Comment