Binary Tree Recursive Insertion

When I added node to the binary tree and tried to show information about it, the information is not displayed. I think I have some link problems in the recursive insertion algorithm, but I cannot fix it.

package test; class BinaryTree<T> { private static class Node<T> { int key; T data; Node<T> leftChild; Node<T> rightChild; public Node(int key,T data) { this.key = key; this.data = data; } } public Node<T> rootNode; public BinaryTree() { rootNode = null; } public Node<T> getRootNode() { return rootNode; } // insert node into binary tree public void insertNode(int key,T data, Node<T> rootNode) { // to create new node // if tree doesn't have root elements if(rootNode == null) { rootNode = new Node<T>(key,data); rootNode.leftChild = null; rootNode.rightChild = null; } else { Node<T> focusNode = rootNode; if(key >= focusNode.key) { insertNode(key,data,focusNode.rightChild); } else { insertNode(key,data,focusNode.leftChild); } } } // inorder traverse tree public void inOrderTraverseTree(Node<T> focusNode) { if(focusNode != null) { inOrderTraverseTree(focusNode.leftChild); System.out.println(focusNode.data); inOrderTraverseTree(focusNode.rightChild); } } } public class MyApp { public static void main(String[] args) { BinaryTree<String> bintree = new BinaryTree<String>(); bintree.insertNode(3, "Boss", bintree.rootNode); bintree.inOrderTraverseTree(bintree.rootNode); } } 

If I add node with this algorithm and try to show the information, it works. How can I fix the problem with a recursive algorithm?

 public void addNode(int key, T name) { Node<T> newNode = new Node<T>(key,name); if(rootNode == null) { rootNode = newNode; } else { Node<T> focusNode = rootNode; Node<T> parent; while(true) { parent = focusNode; if(key < focusNode.key) { focusNode = focusNode.leftChild; if(focusNode == null) { parent.leftChild = newNode; return; } } else { focusNode = focusNode.rightChild; if(focusNode == null) { parent.rightChild = newNode; return; } } } } } 

Thanks for any help.

+4
source share
1 answer

A quick look at your code - I found this part where you check for null, the rootNode variable is local to the function . Therefore, the new Node that you created is discarded immediately after the function completes, it does not change your member field

  // if tree doesn't have root elements if(rootNode == null) { rootNode = new Node<T>(key,data); rootNode.leftChild = null; rootNode.rightChild = null; } 

Instead, you need to use this.rootNode = new Node<T>(key,data); or use a different local variable name to avoid confusion

+3
source

Source: https://habr.com/ru/post/1490189/


All Articles