在樹中搜索最大值
要找到一棵樹(沒有子節點)的最大值,比較左節點和右節點,獲取較大的值(將其儲存在 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
廣告