leetcode 671. Second Minimum Node In a Binary Tree

来源:互联网 发布:linux 变量相加 编辑:程序博客网 时间:2024/05/20 16:34

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.
这道题很简单啊。

按照题意来看, root 肯定是最小值,那么就找 大于root.val 的最小值就好了。

int result=Integer.MAX_VALUE;public int findSecondMinimumValue(TreeNode root) {if(root==null){return -1;}find(root, root.val);if(result==Integer.MAX_VALUE){return -1;}else{return result;}}public void find(TreeNode node,int rootVal){if(node==null){return;}if(node.val>rootVal&&result>node.val){result=node.val;}find(node.left, rootVal);find(node.right, rootVal);}
还有大神用了递归做的,也很不错。

对于左结点和右结点, 如果它们的值都和父结点的值一样的话,继续递归左结点和右结点。
如果它们的值并不是都和父结点的值一样,那么哪个不一样,结果就取哪个的值。如果两个都不一样,那么取两者中较小的那个。

public int findSecondMinimumValue(TreeNode root) {    if (root == null) {        return -1;    }    if (root.left == null && root.right == null) {        return -1;    }        int left = root.left.val;    int right = root.right.val;        // if value same as root value, need to find the next candidate    if (root.left.val == root.val) {        left = findSecondMinimumValue(root.left);    }    if (root.right.val == root.val) {        right = findSecondMinimumValue(root.right);    }        if (left != -1 && right != -1) {        return Math.min(left, right);    } else if (left != -1) {        return left;    } else {        return right;    }}