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 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.
A:
一开始题意没有看清楚。就开始写了 ~~~~~ 哎~~~~~~
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findSecondMinimumValue(TreeNode* root) { if(root == nullptr || root->left == nullptr) return -1; int upper = root->val; int minLeft = helper(root->left, upper); int minRight = helper(root->right, upper); if(minLeft == upper) { return minRight == upper? -1:minRight; } if(minRight == upper) { return minLeft; } // now both are not upper return min(minLeft, minRight); } private: int helper(TreeNode * root, int upper) // return first value bigger than upper, otherwise, return upper { if(root->val > upper) return root->val; if(root->left == nullptr) { return upper; } // now , we have root->val == upper int minLeft = helper(root->left, upper); int minRight = helper(root->right, upper); if(minLeft == upper) return minRight; if(minRight == upper) return minLeft; return min(minLeft, minRight); } };
No comments:
Post a Comment