0%

second-minimum-node-in-a-binary-tree

Second Minimum Node In a Binary Tree – LeetCode 671

Problem

Description

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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
if (!root->left) return -1;
int left = (root->left->val == root->val) ? findSecondMinimumValue(root->left) : root->left->val;
int right = (root->right->val == root->val) ? findSecondMinimumValue(root->right) : root->right->val;
return (left == -1 || right == -1) ? max(left, right) : min(left, right);
}
};

思路

很妙的写法,利用了题目给出的父节点的性质。时间复杂度$O(1)$,空间复杂度$O(n)$。
耗时$0$ ms,排名$0.0\%$

Better

思路

还没看到更好的思路