|
| 1 | +/** |
| 2 | + * 671. Second Minimum Node In a Binary Tree |
| 3 | + * https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * Given a non-empty special binary tree consisting of nodes with the non-negative value, |
| 7 | + * where each node in this tree has exactly two or zero sub-node. If the node has two |
| 8 | + * sub-nodes, then this node's value is the smaller value among its two sub-nodes. More |
| 9 | + * formally, the property root.val = min(root.left.val, root.right.val) always holds. |
| 10 | + * |
| 11 | + * Given such a binary tree, you need to output the second minimum value in the set made |
| 12 | + * of all the nodes' value in the whole tree. |
| 13 | + * |
| 14 | + * If no such second minimum value exists, output -1 instead. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * Definition for a binary tree node. |
| 19 | + * function TreeNode(val, left, right) { |
| 20 | + * this.val = (val===undefined ? 0 : val) |
| 21 | + * this.left = (left===undefined ? null : left) |
| 22 | + * this.right = (right===undefined ? null : right) |
| 23 | + * } |
| 24 | + */ |
| 25 | +/** |
| 26 | + * @param {TreeNode} root |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var findSecondMinimumValue = function(root) { |
| 30 | + return root ? (n => n === Infinity ? -1 : n)(traverse(root, root.val)) : -1; |
| 31 | + function traverse(node, min) { |
| 32 | + if (!node) return Infinity; |
| 33 | + if (node.val > min) return node.val; |
| 34 | + return Math.min(traverse(node.left, min), traverse(node.right, min)); |
| 35 | + } |
| 36 | +}; |
0 commit comments