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. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

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   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

思路:最小值就是根,那么题目变换成找比最小值大一点的最小值;

可以用level order traveral O(N);

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int min = root.val;
        queue.offer(root);
        int diff = Integer.MAX_VALUE;
        int res = -1;
        while(!queue.isEmpty() ) {
            TreeNode node = queue.poll();
            if(node.val > min) {
                if(node.val - min < diff) {
                    diff = node.val - min;
                    res = node.val;
                }
            }
            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        return res;
    }
}

DFS, Divide and Conquer

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        return dfs(root, root.val);
    }
    
    private int dfs(TreeNode root, int min) {
        if(root == null) {
            return -1;
        }
        if(root.val > min) {
            return root.val;
        }
        int leftmin = dfs(root.left, min);
        int rightmin = dfs(root.right, min);
        if(leftmin == -1 || rightmin == -1) {
            return Math.max(leftmin, rightmin);
        } else {
            return Math.min(leftmin, rightmin);
        }
    }
}
发布了673 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105195533