Java – how to find the maximum value in a binary tree
•
Java
I have to complete the method maxelem (node) in this way, and the method maxelem () returns the maximum value contained in the binary tree
How can I do this? I don't know how to do it
public class BinaryTree { protected class Node { protected Integer element; protected Node left; protected Node right; Node(int element) { this.element = element; left = right = null; } Node(int element,Node left,Node right) { this.element = element; this.left = left; this.right = right; } } //end Node class public class NodeReference { private Node node; private NodeReference(Node node) { this.node = node; } public int getElement() { return node.element; } public void setElement(int e) { node.element = e; } } protected Node root; public BinaryTree() { root = null; } private class BoolNode { boolean found; Node node; BoolNode(boolean found,Node node) { this.found = found; this.node = node; } } public int maxElem() { if(root == null) throw new IllegalStateException("Empty tree."); return maxElem(root); } private static int max3(int x,int y,int z) { return max(x,max(y,z)); } private int maxElem(Node node) { //... } }
Thank you.
Solution
Try:
private int maxElem(Node node) { int max = node.element; if(node.left != null) { max = Math.max(max,maxElem(node.left)); } if(node.right != null) { max = Math.max(max,maxElem(node.right)); } return max; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码