在树中搜索最大值
要找到一棵树(没有子节点)的最大值,比较左节点和右节点,获取较大的值(将其存储在 max 中),然后将其与根节点的值进行比较。
如果结果 (max) 更大,那么它是树的最大值,否则根节点是树的最大值。
要获得整个二叉树的最大值,获取左子树的最大值、右子树的最大值以及根节点。现在比较这三个值,这三个值中较大的值就是树的最大值。
示例
class Node{
int data;
Node leftNode, rightNode;
Node() {
leftNode = null;
rightNode = null;
this.data = data;
}
Node(int data) {
leftNode = null;
rightNode = null;
this.data = data;
}
int getData() {
return this.data;
}
Node getleftNode() {
return this.leftNode;
}
Node getRightNode() {
return this.leftNode;
}
void setData(int data) {
this.data = data;
}
void setleftNode(Node leftNode) {
this.leftNode = leftNode;
}
void setRightNode(Node rightNode) {
this.leftNode = rightNode;
}
}
public class MaxValueInBinaryTree {
public static void main(String[] args){
Node node = new Node(50);
node.leftNode = new Node(60);
node.leftNode.leftNode = new Node(45);
node.leftNode.rightNode = new Node(64);
node.rightNode = new Node(60);
node.rightNode.leftNode = new Node(45);
node.rightNode.rightNode = new Node(64);
System.out.println("Maximum value is "+maximumValue(node));
}
public static int maximumValue(Node root) {
int max = 0;
if(root!=null) {
int lMax = maximumValue(root.leftNode);
int rMax = maximumValue(root.rightNode);;
if(lMax>rMax){
max = lMax;
} else {
max = rMax;
}
if(root.data>max) {
max = root.data;
}
}
return max;
}
}
输出
Maximum value is 64
广告