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);
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章