Second Minimum Node In a Binary Tree问题及解法

来源:互联网 发布:华师网络教育平台 编辑:程序博客网 时间:2024/06/05 00:46

问题描述:

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.

示例:

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.

问题分析:

利用DFS寻找树中第二小的值。


过程详见代码:

/** * 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) {int second = -1;bl(root, root->val, second);return second;}void bl(TreeNode* root, int first,int& second){if (root == nullptr) return;if (root->val > first && (root->val < second || second == -1)){second = root->val;}bl(root->left, first, second);bl(root->right, first, second);}};


阅读全文
0 0