1. 程式人生 > 實用技巧 >Leetcode 二叉樹中第二小的節點

Leetcode 二叉樹中第二小的節點

Leetcode 二叉樹中第二小的節點

題目定義:

給定一個非空特殊的二叉樹,每個節點都是正數,並且每個節點的子節點數量只能為2或0。
如果一個節點有兩個子節點的話,那麼該節點的值等於兩個子節點中較小的一個。

更正式地說,root.val = min(root.left.val, root.right.val) 總成立。

給出這樣的一個二叉樹,你需要輸出所有節點中的第二小的值。如果第二小的值不存在的話,輸出 -1 。

示例 1:
                 2
    	        / \
               2   5
                  / \
                 5   7 
    
輸入:root = [2,2,5,null,null,5,7]
輸出:5
解釋:最小的值是 2 ,第二小的值是 5 。  
    
示例 2:
                2
               / \ 
              2   2

輸入:root = [2,2,2]
輸出:-1
解釋:最小的值是 2, 但是不存在第二小的值。

使用set 儲存所有節點值並排序:

class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        if(root == null)
            return -1;
        Set<Integer> set = new HashSet<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(queue.size() > 0){
            TreeNode node = queue.poll();
            set.add(node.val);
            if(node.left != null)
                queue.offer(node.left);
            if(node.right != null)
                queue.offer(node.right);
        }
        List<Integer> result = new ArrayList<>(set);
        Collections.sort(result);
        if(result.size() == 1)
            return -1;
        else 
            return result.get(1);
    }
}

使用min 儲存最小的節點:

/*
* 思路: 使用min 儲存根節點的值(最小值),遞迴遍歷所有節點,當遞迴到的節點大於最小值,
*	    則返回該值並與其他節點對比,若兩個節點都大於min 則取最小的那個值
*       若 有節點小於 min(遍歷到空節點,會返回 -1) ,則取所有值中最大的那個
*/
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        if(root == null)
            return -1;
        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 left = dfs(root.left,min);
        int right = dfs(root.right,min);
        if(left > min && right > min)
            return Math.min(left,right);
        else 
            return Math.max(left,right);
    }
}