[LeetCode] 671. Second Minimum Node In a Binary Tree

A second node of the binary tree is small. Given a non-null binary particular, each of the nodes are positive, and the number of child nodes of each node can only be 0 or 2. If a node has two child nodes, then the value of this node is not greater than the value of its child nodes. Given such a binary tree, you need to output a second small value in all nodes. If the second small value does not exist, the output of -1. example,

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.

This question is much like the 230 title , but this question is not BST but an ordinary binary tree. Since the topic that the value of each parent must be less than equal to his child node, and then find the node is the second smallest, so you can be sure that the tree root root of val must be minimal. Therefore, to set up a variable to remember the value and a root Integer.MAX_VALUE, then preorder tree, if any node has a value of between root.val and Integer.MAX_VALUE, then the second smallest front node to find.

Time O (n)

Space O (n)

Java implementation

 1 class Solution {
 2     int min1;
 3     long res = Long.MAX_VALUE;
 4 
 5     public int findSecondMinimumValue(TreeNode root) {
 6         min1 = root.val;
 7         dfs(root);
 8         return res < Long.MAX_VALUE ? (int) res : -1;
 9     }
10 
11     public void dfs(TreeNode root) {
12         if (root != null) {
13             if (min1 < root.val && root.val < res) {
14                 res = root.val;
15             } else if (min1 == root.val) {
16                 dfs(root.left);
17                 dfs(root.right);
18             }
19         }
20     }
21 }

 

JavaScript implementation

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number}
 4  */
 5 var findSecondMinimumValue = function (root) {
 6     let min1;
 7     let res = Infinity;
 8     if (root != null) {
 9         min1 = root.val;
10     }
11 
12     var helper = function (root) {
13         if (root != null) {
14             if (min1 < root.val && root.val < res) {
15                 res = root.val;
16             } else if (min1 == root.val) {
17                 helper(root.left);
18                 helper(root.right);
19             }
20         }
21     }
22     helper(root);
23     return res < Infinity ? res : -1;
24 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12529272.html
Recommended