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 treenodestruct 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 *root, int min1, int &secMin){if (!root)return;if (root->data > min1 && root->data <= secMin){secMin = root->data;flag = true;}dfs(root->left, min1, secMin);dfs(root->right, min1, secMin);}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(root, root->data, secMin);if (flag == true)return secMin;elsereturn -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