程序媛詹妮弗
终身学习

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 }

 

posted on 2018-05-22 03:15  程序媛詹妮弗  阅读(91)  评论(0编辑  收藏  举报