在Java中查找二进制树中的最大元素
时间:2020-02-23 14:34:11 来源:igfitidea点击:
在本教程中,我们将看到关于在Java中的二叉树中找到最大元素的程序。
它可以有两个解决方案。
- 递归
- 迭代
递归解决方案:
算法 :
在二进制树中获取最大元素的步骤:
- 在左子树中查找最大元素
- 在右子树中查找最大元素
- 将上述子树的最大值与当前节点进行比较
- 我们将找到具有上述步骤的最大元素
递归的代码将是:
//Recursive Solution
/* To get max node in a binary tree*/
//Recursive Solution
/* To get max node in a binary tree*/
public static int getMaximumRec(TreeNode root)
{
int max=Integer.MIN_VALUE;
int value=0;
int left,right;
if(root != null)
{
value=root.data;
left=getMaximumRec(root.left);
right=getMaximumRec(root.right);
if(left>right)
{
max=left;
}
else
{
max=right;
}
if(max < value)
{
max=value;
}
}
return max;
}
迭代解决方案:
迭代解决方案将类似于级别遍历遍历。
当我们从队列中弹出元素时,我们将检查最多。
迭代的代码将是:
//Iterative Solution
/* To get max node in a binary tree*/
public static int getMaximumItr(TreeNode startNode) {
Queue<TreeNode> queue=new LinkedList<>();
queue.add(startNode);
int max=Integer.MIN_VALUE;
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
if(max < tempNode.data)
max=tempNode.data;
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
return max;
}
允许创建Java程序以在二进制树中获取最大元素:
让我们说,你的二叉树是这样的:
package org.igi.theitroad.binarytree;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTreeGetMaxElement {
/*
* @Author : igi Mandliya
*/
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
//Recursive Solution
/* To get max node in a binary tree*/
public static int getMaximumRec(TreeNode root)
{
int max=Integer.MIN_VALUE;
int value=0;
int left,right;
if(root != null)
{
value=root.data;
left=getMaximumRec(root.left);
right=getMaximumRec(root.right);
if(left>right)
{
max=left;
}
else
{
max=right;
}
if(max < value)
{
max=value;
}
}
return max;
}
//Iterative Solution
/* To get max node in a binary tree*/
public static int getMaximumItr(TreeNode startNode) {
Queue<TreeNode> queue=new LinkedList<>();
queue.add(startNode);
int max=Integer.MIN_VALUE;
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
if(max < tempNode.data)
max=tempNode.data;
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
return max;
}
public static void main(String[] args)
{
//Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Max node using recursion :"+getMaximumRec(rootNode));
System.out.println("Max node using iteration :"+getMaximumItr(rootNode));
}
public static TreeNode createBinaryTree()
{
TreeNode rootNode =new TreeNode(40);
TreeNode node20=new TreeNode(20);
TreeNode node10=new TreeNode(10);
TreeNode node30=new TreeNode(30);
TreeNode node60=new TreeNode(60);
TreeNode node50=new TreeNode(50);
TreeNode node70=new TreeNode(70);
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
}
}
运行上面的程序,我们将获取以下输出:
Max node using recursion :70 Max node using iteration :70

