Second Minimum Node In a Binary Tree【特定数中第二小的数】

PROBLEM:

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

If no such second minimum value exists, output -1 instead.

意思就是:给定一个由非负值节点组成的非空特殊二叉树,其中该树中的每个节点具有恰好两个或零个子节点。 如果该节点有两个子节点,则该节点的值是其两个子节点中较小的值。给定这样的二叉树,您需要输出由整个树中的所有节点值组成的集合中的第二个最小值。如果不存在这样的第二最小值,则输出-1。

Example 1:

Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

SOLVE:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
//自己写的函数
class Solution {
public:
    int findSecondMinimumValue(TreeNode* root) {
        int min=root->val;
        int secondMin=toFindSecondMinimumValue(root,min);
        if(secondMin==INT_MAX)
            //将INT_MAX替换为-1
            return -1;
        return secondMin;
    }
    int toFindSecondMinimumValue(TreeNode* root,int min){
        //函数可能返回第二小的数字,也可能返回最小的数
        if(!root->left&&!root->right){
            if(root->val==min)
                return INT_MAX;    //用最大的正整数代替,不然无法用“left<right?left:right”返回
            else
                return root->val;
        }
        int left=root->left->val;    //初始化为子树根节点值,如果其值和整棵树的最小值相等则需要更新
        int right=root->right->val;    //同上
        if(root->left->val==min)
            //如果子树的根节点值和整棵树的最小值相等时,继续求其下的第二小节点
            left=toFindSecondMinimumValue(root->left,min);
        if(root->right->val==min)
            //同上
            right=toFindSecondMinimumValue(root->right,min);
        return left<right?left:right;
    }
};
//人家写的,确实要精简很多
//首先没有用INT_MAX,看到-1直接返回另一个,否则返回小的那个
//其次直接判断当前节点而不是判断它的两个子节点
class Solution {
public:
    int findSecondMinimumValue(TreeNode* root) {
        if (!root) return -1;
        int ans = minval(root, root->val);
        return ans;
    }
private:
    int minval(TreeNode* p, int first) {
        if (p == nullptr) return -1;
        if (p->val != first) return p->val;
        int left = minval(p->left, first), right = minval(p->right, first);
        // if all nodes of a subtree = root->val, 
        // there is no second minimum value, return -1
        if (left == -1) return right;
        if (right == -1) return left;
        return min(left, right);
    }
};



猜你喜欢

转载自blog.csdn.net/sim0hayha/article/details/80170099