zoukankan      html  css  js  c++  java
  • 最大二叉搜索子树

    有一棵二叉树,其中所有节点的值都不一样,找到含有节点最多 的搜索二叉子树,并返回这棵子树的头节点.

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class MaxSubtree {
    11 public:
    12     TreeNode* getMax(TreeNode* root) {
    13         // write code here
    14         int max, min, num;   // 二叉搜索树的最小值,最大值,节点数
    15         return max_node_subtree(root, max, min, num);
    16         }
    17     
    18     TreeNode* max_node_subtree(TreeNode* root, int& maxVal, int& minVal, int&num){
    19         if(root == NULL){
    20             maxVal = INT_MIN;
    21             minVal = INT_MAX;
    22             num = 0;
    23             return NULL;
    24         }
    25         
    26         int lmax, lmin, lnum;
    27         TreeNode* lnode = max_node_subtree(root->left, lmax, lmin, lnum);
    28         int rmax, rmin, rnum;
    29         TreeNode* rnode = max_node_subtree(root->right, rmax, rmin, rnum);
    30         
    31         maxVal = max(rmax,root->val);// 更新最大值
    32         minVal = min(lmin,root->val);// 更新最小值
    33         
    34         if(lmax<root->val && rmin>root->val && lnode==root->left && rnode==root->right){
    35             num = lnum+rnum+1;// 更新节点个数
    36             return root;// 返回头节点
    37         }
    38         
    39         if(lnum>rnum){// 说明不满足上面的条件 选择左右节点中较多节点的子树更新节点个数
    40             num = lnum;
    41             return lnode;
    42         }else{
    43             num = rnum;
    44             return rnode;
    45         }
    46     }
    47     
    48     
    49 };
  • 相关阅读:
    #Leetcode# 448. Find All Numbers Disappeared in an Array
    #Leetcode# 65. Valid Number
    #Leetcode# 37. Sudoku Solver
    #Leetcode# 25. Reverse Nodes in k-Group
    POJ 3264 Balanced Lineup
    HDU 3947 Assign the task
    Codeforces Round #546 (Div. 2)
    2019.08.18【NOIP?提高组】模拟 A 组 总结
    jzoj 6307. 安排
    jzoj 6305. 最小值
  • 原文地址:https://www.cnblogs.com/sclczk/p/11155390.html
Copyright © 2011-2022 走看看