题目
给定一颗二叉树,已知其中所有节点的值都不一样,找到含有节点最多的二叉搜索树,并返回头节点。
注:一个二叉树的子树的叶节点必须是该二叉树的叶节点。
解答:
以节点root为头的树中,最大的二叉搜索树只可能来自以下两种情况。
1.如果来自root左子树上的最大ST以root.left为头,来自root右子树上的最大ST以root.right 为头,且左边BST的最大值小于root.val,且右边BST的最小值大于root.val。那么,
以节点root为根节点的正棵树都是ST。
2.不满足条件1的话,以root为根的树的最大ST是来自左子树的最大ST和右子树的最大ST中包含节点树较多的那一个。
通过以上分析,求解过程如下:
1.整体过程是二叉树的后序遍历。
2.用recorder[]记录相关数据。
public class Solution {
public TreeNode biggestSubBST(TreeNode root)
{
if(root == null)
return null;
int[] recorder=new int[3];//记录二叉树的节点个数,最大值和最小值
return postorder(root,recorder);
}
public TreeNode poseorder(TreeNode root,int[] recorder)
{
if(root == null)
{
recorder[0]=0;
recorder[1]=Integer.MIN_VALUE;
recorder[2]=Integer.MAX_VALUE;
return null;
}
TreeNode left=postorder(root.left,recorder);
int lsize=recorder[0];
int lmax=recorder[1];
int lmin=recorder[2];
TreeNode right=postorder(root.right,recorder);
int rsize=recorder[0];
int rmax=recorder[1];
int rmin=recorder[2];
recorder[1]=Math.max(rmax, root.val);
recorder[2]=Math.min(lmin, root.val);
if(root.left == left&&root.right == right&&root.val > lmax&&root.val < rmin)
{
recorder[0]=lsize+rsize+1;
return root;
}else
{
if(lsize > rsize)
{
recorder[0]=lsize;
return left;
}else
{
recorder[0]=rsize;
return right;
}
}
}
}