有一棵二叉树,其中所有节点的值都不一样,找到含有节点最多 的搜索二叉子树,并返回这棵子树的头节点.
给定二叉树的头结点root,请返回所求的头结点,若出现多个节点最多的子树,返回头结点权值最大的。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class MaxSubtree {
public:
TreeNode* getMax(TreeNode* root) {
// write code here
int record[3] = {0,0,0};
if(root == NULL)
return NULL;
return getMax(root,record);
}
TreeNode* getMax(TreeNode* root,int*record){
if(root == NULL)
{
record[0] = 0;
record[1] = INT_MAX;//最小
record[2] = INT_MIN;//最大
return NULL;
}
int val = root->val;
TreeNode*lNode = getMax(root->left,record);
int lsize=record[0];
int lmin=record[1];
int lmax=record[2];
TreeNode*rNode = getMax(root->right,record);
int rsize=record[0];
int rmin = record[1];
int rmax=record[2];
record[1] = min(lmin,val);
record[2] = max(rmax,val);
if(lNode == root->left&&rNode == root->right&&lmax<val&&val<rmin)
{
record[0] = lsize+rsize+1;
return root;
}
else
{
if(lsize>rsize)
{
record[0] = lsize;
return lNode;
}
else
{
record[0] = rsize;
return rNode;
}
}
}
};