lintcode 1094. binary tree times smaller nodes

Given a particular non-empty node comprising a non-negative binary tree, wherein each node in the tree contains exactly zero or two child nodes. If the node has two child nodes, then the node is not greater than the value of its two child nodes.

For such a binary tree, you need to output a small value of a sub-set constituted value among the nodes of the entire tree.

If there is no such a small time value, the output of -1 instead.

样例
样例1:

输入: 
    2
   / \
  2   5
     / \
    5   7

输出: 5
解释: 最小的值是2,次小值是5.
样例2:

输入: 
    2
   / \
  2   2

输出: -1
解释: 最小值是2,但是没有次小值.

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root
     * @return: the second minimum value in the set made of all the nodes' value in the whole tree
     */
    int findSecondMinimumValue(TreeNode * root) {
        // Write your code here
        recursion(root);
        int res=tmp[0];
        for (int i = 0; i < tmp.size(); i++) {
            /* code */
            if(tmp[i]!=res)return tmp[i];
        }
        return -1;
    }
     void recursion(TreeNode*root)
    {
        if(root==NULL) return;
        tmp.push_back(root->val);
        recursion(root->left);
        recursion(root->right);
    }
    private:std::vector<int> tmp;
};
Published 369 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43981315/article/details/103956355