• [leetcode]671. 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.

    Example 1:

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

    Example 2:

    Input: 
        2
       / 
      2   2
    
    Output: -1
    Explanation: The smallest value is 2, but there isn't any second smallest value.

    题意:

    求二叉树次小结点

    Solution1:DFS

    code

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11 
    12     int second = Integer.MAX_VALUE;
    13     
    14     public int findSecondMinimumValue(TreeNode root) {
    15         if(root==null)  return -1;
    16         helper(root, root.val);
    17         return second == Integer.MAX_VALUE ? -1 : second;
    18     }
    19 
    20     public void helper(TreeNode node, int rootVal){
    21         if(node == null){return;}
    22         
    23         if(node.val > rootVal && second > node.val){
    24             second = node.val;
    25         }
    26         
    27         helper(node.left, rootVal);
    28         helper(node.right, rootVal);
    29     }
    30 }
  • 相关阅读:
    [CodeForces
    [CodeChef]RIN(最小割)
    [Bzoj3894]文理分科(最小割)
    [Poj3469]Dual Core CPU(最小割)
    MySQL- 锁(3)
    MySQL- 锁(1)
    MySQL- 锁(2)
    MySQL-中文全文检索
    Solr
    多线程编程-之并发编程:同步容器
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9070192.html
Copyright © 2020-2023  润新知