java - Find a value in a binary tree avoiding stackoverflow exception -


i'm trying find value in binary tree , returning node has value i'm looking for.

i did algorithm works when value not in deep level of tree, when value in deep position java.lang.stackoverflowerror. here code:

class node {      // keep these​​​​​​​​‌‌‌‌‌​​‌‌​​​​​​‌​‌​‌‌‌​ fields     node left, right;     int value;      public node find(int v){         if(v > this.value && this.right != null)             return right.find(v);         if(v < this.value && this.left != null)             return left.find(v);         if(this.value == v)             return this;         return null;     } } 

can 1 suggest me solution issue (i heard tail optimization recursion) i'm not sure of working in java.

the simplest approach convert while loop, maintains state of "the current node we're testing".

on each iteration of loop, there 3 possibilities:

  • the current node has right value, in case can return it
  • the current node has subnode on correct "side", in case can continue iterating subnode new "current node"
  • neither of above case, in case value isn't found , can return null

so like:

public node find(int v) {     node current = this;     while (current != null) {         if (current.value == v) {             return current;         }         // drop out of loop naturally if there's no appropriate subnode         current = v < current.value ? current.left : current.right;     }     return null; } 

or less code, perhaps less readably:

public node find(int v) {     node current = this;     // keep navigating down tree until either we've run     // out of nodes at, or we've found right value.     while (current != null && current.value != v) {         current = v < current.value ? current.left : current.right;     }     return current; } 

Comments

Popular posts from this blog

Add new key value to json node in java -

javascript - Highcharts Synchronized charts with missing data points -

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -