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

二叉树中第二小的节点。给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。例子,

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.

这道题很像230题但是这道题不是BST而是一棵普通的二叉树。既然题目说了每个父节点的值一定小于等于他的子节点,然后找的又是第二小的节点,所以可以肯定的是这棵树的根节点root的val一定是最小的。所以先设置一个变量记住这个根节点的值和一个Integer.MAX_VALUE,然后前序遍历这棵树,如果有任何节点的值介于root.val和Integer.MAX_VALUE之间,则这个第二小的节点就找到了。

时间O(n)

空间O(n)

Java实现

 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实现

 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 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12529272.html