题目描述:
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.
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
if(root==NULL) return -1;
int result=-1;
preorder(root,root->val,result);
return result;
}
void preorder(TreeNode* root, int min_val, int& result)
{
if(root==NULL) return;
if((result==-1||root->val<result)&&root->val!=min_val) result=root->val;
preorder(root->left,min_val,result);
preorder(root->right,min_val,result);
}
};
本文探讨了一种特殊二叉树的遍历算法,旨在找出树中所有节点值的第二最小值。通过先序遍历策略,文章详细介绍了如何在保持时间效率的同时,避免重复计算,最终解决寻找二叉树第二小节点值的问题。
392

被折叠的 条评论
为什么被折叠?



