[Leetcode] Second Minimum Node in a Binary Tree topic
https://leetcode.com/problems/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 have ex actly or Zero sub-node. If the node has both sub-nodes, then this node's value is the smaller value among its-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.
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 second small EST value.
Code
34/34 test cases passed.
Runtime:0 ms
/** * Definition for a binary tree node.
* struct TreeNode {* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* }; */#define INF 0x7fffffff//The minimum value (different from the minimum value of root->val) int traverse (struct treenode* node, struct Treenod) when node nodes are found as subtree
e* root) {int lval = INF;
if (node->left! = NULL) {lval = Traverse (node->left, Root);
} int rval = INF;
if (node->right! = NULL) {rval = Traverse (node->right, Root);
} int val = INF;
if (node->val! = root->val) {val = node->val;
} if (lval! = root->val) {if (val > lval) {val = lval;
}} if (Rval! = root->val) {if (val > Rval) {val = rval;
}} return Val;
} int Findsecondminimumvalue (struct treenode* root) {if (root = = NULL) {return-1;
} if (root->left = = NULL && Root->right = = null) {return-1; } int val = INF; val = Traverse (root, root);//val = inf because there is no value different from Root->val if (val = = Root->val | | val = = INF) {return
-1;
} else {return val; }
}