LeetCode#671 Second Minimum Node In a Binary Tree (week13)

week13

題目

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.
這裏寫圖片描述

原題地址:https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/

解析

題目要求找出給定二叉樹的第二小元素(如果沒有返回-1)
大致解題思路爲:遍歷該樹,用兩個整數記錄目前找到的最小的元素A和第二小的元素B,找到比目前最小元素A更小的元素C則用A替代B成爲第二小元素,C替代A成爲最小元素;如果找到的元素C大於A但小於B,則直接用C代替B成爲新的第二小元素。

代碼

class Solution {
public:
    int findSecondMinimumValue(TreeNode* root) {
        int min = 1000000, secondMin = 1000001;
        recursiveFind(root, min, secondMin);
        if (secondMin == 1000000) {
            return -1;
        }
        else {
            return secondMin;
        }
    }
    void recursiveFind(TreeNode* root, int &min, int &secondMin) {
        if (root) {
            if (root->val < min) {
                secondMin = min;
                min = root->val;
            }
            else if (root->val < secondMin && root->val!= min){
                secondMin = root->val;
            }
            if (root->left) {
                recursiveFind(root->left, min, secondMin);
            }
            if (root->right) {
                recursiveFind(root->right, min, secondMin);
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章