java - Finding Inorder Successor in Binary Search Tree -


I am creating a binary search tree class, I got all my actions accepting the successor.

My tree input 30 10 45 38 20 50 25 33 8 12

When I print inland traversal it comes up

8 10 12 20 25 30 33 38 45 50

When I put value 8, it says that its successor is 12. This is also for input 10 and 12.

When I enter value 33 then it says that the successor is 50. Its not

I can not fix it Any help of suggestions would be appreciated.

I'm calling it primarily:

  BinarySearchTree BST = new BinarySearchTree (array); BST.getSeccessor (a); // Where is a user input to find this successor   

The following is my code ...

  Public TreeNode successor (tree node node) { If (node ​​== faucet) returns node; If (node. Right! = Null) {return leftmonod (node ​​right); } Treeoid y = node. Parent; While (empty! = Y & amp; y.right) .equals (node)) {node = y; Y = y.parent; } Return y; } Public stable TreeNode left modode (tree node node) {if (null == node) {return tap; } While (zero! = Node. Left) {node = node. Left; } Return node; } / ** Search value in the tree ** for success / public triode search (int key) {tree_node node = root; While (node! = Null) {if (key & lt; node.value) {node = node.left; } And if (key> node.value) {node = node.right; } Return node; } Return tap; } / ** The successor of the given value ** / Public Ink Recipient (Int. Values) {TreeNodeNode = Heir (Search (Val)); Return node.value; } << Code>   

I work solution based on pseudo code in Nicklus Is added Answer:

  Public TreeNode successor (tree node) {if (node ​​== faucet) return node; If (node. Right! = Null) {return leftmonod (node ​​right); } While (zero! = Node.parent / * as long as we are not root / /and amp; node.parent.right == node) / * and as long as we have the "right" node * / {node = node; // go up one level) return node Parent; }   

To work for this, you must fix the implementation of some of your methods (given below):

  / ** of the tree Required search value for successor ** / public triode search {int key} {TreeNode node = root; While (node! = Null & amp; amp; key; = node.value) {if (key  node.value) {node = node.right; }} Return node; } / ** The successor of the given value ** / Public Ink Recipient (Ent Vale) {Tree node node; If (null == (node ​​= search (wal)) || (null == (node ​​= successor (node))) {// neither wall is in BST, or this is the last value-> no successor ERROR_CODE; // -1 for example;} return node.value;}    

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -