找到最大值必須完成的方法maxElem(節點節點),該方法maxElem()返回最大值包含在二叉樹這樣的方式。如何二叉樹
我該怎麼做?我不知道該怎麼做..
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) {
//...
}
}
非常感謝!
由於這看起來像一個家庭作業,我認爲這將是更適當的解釋遞歸遍歷樹的原則,而不僅僅是給他的代碼。 – kenor
@Vakh謝謝瓦赫! – user3425699