Second Minimum Node In a Binary Tree

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. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

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.

Example:

Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};

bool flag = false;
void dfs(TreeNode *rootint min1int &secMin)
{
    if (!root)
        return;
    if (root->data > min1 && root->data <= secMin)
    {
        secMin = root->data;
        flag = true;
    }
    dfs(root->leftmin1secMin);
    dfs(root->rightmin1secMin);
}
int findSecondMinimumValue(TreeNode *root)
{
    if (root == NULL)
        return -1;
    if (root->left == NULL && root->right == NULL)
        return -1;
    int secMin = INT_MAX;
    flag = false;
    dfs(rootroot->datasecMin);
    if (flag == true)
        return secMin;
    else
        return -1;
}

int main()
{
    TreeNode *root = new TreeNode(2);
    root->left = new TreeNode(2);
    root->right = new TreeNode(5);
    root->right->left = new TreeNode(5);
    root->right->right = new TreeNode(7);

    cout << findSecondMinimumValue(root);

    return 0;
}


No comments:

Post a Comment