Second Minimum Node In a Binary Tree

题目

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.

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.

答案

class Solution {
    /*
        The minimum value is always the root, but what about the second minimum?
        try to find the minimum value of the left and right tree
    */
    public int findSecondMinimumValue(TreeNode root) {
        if(root == null) return -1;
        int ret = findmin(root, root.val);
        if(ret == Integer.MAX_VALUE) return -1;
        return ret;
    }
    
    public int findmin(TreeNode root, int exclude) {
        if(root == null) return Integer.MAX_VALUE;
        int left = findmin(root.left, exclude);
        int right = findmin(root.right, exclude);
        
        int rootval = root.val;
        if(left == exclude) left = Integer.MAX_VALUE;
        if(right == exclude) right = Integer.MAX_VALUE;
        if(rootval == exclude) rootval = Integer.MAX_VALUE;
        return Math.min(rootval, Math.min(left, right));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容