zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    IDEA搭建《算法》第四版的开发环境
    tomcat源码环境搭建
    cap定理
    idea jdk 源码搭建
    2020-04-07 学习记录
    idea 格式化代码
    Ajax工作原理
    prototype封装继承
    作用域
    原型链的原理
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9070192.html
Copyright © 2011-2022 走看看