Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 3, 2017 01:58
Show Gist options
  • Select an option

  • Save cixuuz/a675e3a3893a2d32accfff1386fe60bd to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/a675e3a3893a2d32accfff1386fe60bd to your computer and use it in GitHub Desktop.
[671. Second Minimum Node In a Binary Tree] #leetcode
class Solution {
// O(n) O(h)
public int findSecondMinimumValue(TreeNode root) {
if (root == null) return -1;
return dfs(root, root.val);
}
private int dfs(TreeNode node, int largest) {
if (node == null) return -1;
if (node.val > largest) return node.val;
int left = dfs(node.left, largest);
int right = dfs(node.right, largest);
if (left == -1 && right == -1) return -1;
if (left == -1) return right;
if (right == -1) return left;
return Math.min(left, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment