【发布时间】:2016-03-27 20:32:27
【问题描述】:
import java.util.*;
class Node
{
int data;
Node left , right;
public Node (int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
public static Node root;
BinaryTree()
{
root = null;
}
public int largestBST(Node root)
{
MinMax m = largest(root);
return m.size;
}
public MinMax largest(Node root)
{
if(root == null)
{
return new MinMax();
}
MinMax leftMinMax = largest(root.left);
MinMax rightMinMax = largest(root.right);
MinMax m = new MinMax();
if(leftMinMax.isBST == false || rightMinMax.isBST == false || (leftMinMax.max > root.data) || (rightMinMax.min <= root.data))
{
m.isBST = false;
m.size = Math.max(leftMinMax.size , rightMinMax.size);
}
m.isBST = true;
m.size = leftMinMax.size + rightMinMax.size + 1;
m.min = root.left != null ? leftMinMax.min : root.data;//if left node is null take node as min or min of left
m.max = root.right != null ? rightMinMax.max : root.data;//if right node is null take node as max or max of right
return m;
}
class MinMax
{
int max,min;
boolean isBST;
int size;
MinMax()
{
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
isBST = false;
size = 0;
}
}
public static void main(String args[])
{
BinaryTree bt = new BinaryTree();
bt.root = new Node(25);
bt.root.left = new Node(18);
bt.root.right = new Node(50);
bt.root.left.left = new Node(19);
bt.root.left.right = new Node(20);
bt.root.right.left = new Node(35);
bt.root.right.right = new Node(60);
bt.root.right.left.right = new Node(40);
bt.root.right.left.left = new Node(20);
bt.root.right.right.left = new Node(55);
bt.root.right.right.right = new Node(70);
int size = bt.largestBST(root);
System.out.println("The size of largest BST is " + size);
}
}
这里的输出应该是 7,但它显示的是树中的节点总数,即 11。
代码有什么问题?
【问题讨论】:
-
旁注:如果可能,学习如何编写单元测试。使用 Junit 进行测试效率更高;与使用静态电源相比。
-
我认为你应该澄清“二叉树中最大的BST”的定义。
-
这不是回答同一个问题吗? stackoverflow.com/questions/2336148/…
-
你在寻找最大的子树吗?换句话说,是否要查看左子树是否小于/大于右子树,反之亦然,然后返回最大的大小?
-
是的,我想找到最大的二叉搜索树,即左边比节点小,右边比节点大。
标签: java recursion binary-search-tree