669. Trim a Binary Search Tree

来源:互联网 发布:拓展人脉的软件 编辑:程序博客网 时间:2024/06/06 13:59

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly twoor 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.

Example 1:

Input:     2   / \  2   5     / \    5   7Output: 5Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input:     2   / \  2   2Output: -1Explanation: The smallest value is 2, but there isn't any second smallest value.
根节点和子节点的一个是相等的,另外一个可能要大,也可能相等。返回树的次小值

这个题考察递归。关键点是把根节点的值和下面的值进行比较


class Solution {public:    int findSecondMinimumValue(TreeNode* root) {      if(root==nullptr) return -1;        else            return minSPoint(root,root->val);            }    int minSPoint(TreeNode* root,int first){        if(root==nullptr) return -1;        if(root->val!=first) return root->val;        int left=minSPoint(root->left,first);        int right=minSPoint(root->right,first);        if(left==-1) return right;        if(right==-1) return left;        return min(left,right);//如果两个都不是-1,说明两个值都是比first大的,因为如果和first相等,最后一定是到尾部返回-1。    }};

原创粉丝点击