Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Recursive implementation of finding minimum value in a generic binary tree: Here is the BinaryTreeNode class:</strong> </p> <pre><code>package binaryTrees; public class BinaryTreeNode { private int data; private BinaryTreeNode left; private BinaryTreeNode right; private int max; private int min; public int getMax() { return BinaryTreeOps.maxValue(this); } public int getMin() { return BinaryTreeOps.minValue(this); } public BinaryTreeNode(){ } public BinaryTreeNode(int data){ this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public BinaryTreeNode getLeft() { return left; } public void setLeft(BinaryTreeNode left) { this.left = left; } public BinaryTreeNode getRight() { return right; } public void setRight(BinaryTreeNode right) { this.right = right; } } </code></pre> <p><strong>Here is the BinaryTreeOps class with the minValue operation: The crux is to use a static variable min so that we reset the same static variable every time we find a value lower than the previous value. It returns zero if pass a null node. You can modify this behaviour as per you requirement.</strong></p> <pre><code>package binaryTrees; public class BinaryTreeOps { private static int min; public static int minValue(BinaryTreeNode node){ min=node.getData(); //imp step, since min is static it is init by 0 minValueHelper(node); return min; } public static void minValueHelper(BinaryTreeNode node){ if(node==null) return; if(node.getData()&lt;min) min=node.getData(); if(node.getLeft()!=null &amp;&amp; node.getLeft().getData()&lt;min) min=node.getLeft().getData(); if(node.getRight()!=null &amp;&amp; node.getRight().getData()&lt;min) min=node.getRight().getData(); minValueHelper(node.getLeft()); minValueHelper(node.getRight()); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload