gpt4 book ai didi

java - 如何在二叉树中找到最大值

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:33:32 25 4
gpt4 key购买 nike

我必须以 ma​​xElem() 方法返回二叉树中包含的最大值的方式完成方法 ma​​xElem(Node node)

我该怎么做?我不知道该怎么做..

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) {
//...
}

}

非常感谢!

最佳答案

尝试:

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;
}

关于java - 如何在二叉树中找到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com