671. 二叉树中第二小的节点

2021-07-27 LeetCode每日一题

``````输入：root = [2,2,5,null,null,5,7]

``````输入：root = [2,2,2]

• 树中节点数目在范围 [1, 25] 内
• 1 <= Node.val <= 231 - 1
• 对于树中每个节点 root.val == min(root.left.val, root.right.val)

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
StringBuilder sb = new StringBuilder();
dfs(sb, root);
String[] str = sb.substring(0, sb.length() - 1).toString().split(",");
int[] array = Arrays.stream(str).mapToInt(Integer::parseInt).toArray();
Arrays.sort(array);
int len = array.length;
int min = array[0];
for (int i = 1; i < len; i++) {
if (array[i] > min) {
return array[i];
}
}

return - 1;
}

private void dfs(StringBuilder sb, TreeNode node) {
if (node.left == null && node.right == null) {
sb.append(node.val).append(",");
return;
}

dfs(sb, node.left);
dfs(sb, node.right);
}
}

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode() {}
*     TreeNode(int val) { this.val = val; }
*     TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
class Solution {
int min = -1;
public int findSecondMinimumValue(TreeNode root) {
dfs(root, root.val);
return min;
}

private void dfs(TreeNode node, int val) {
if (node == null) {
return;
}
if (node.val != val) {
// 第一个比根节点大的值
if (min == -1) {
min = node.val;
} else {
min = Math.min(min, node.val);
}
// 不需要往下搜索了，因为下面的值都比当前节点的值更大
return;
}

dfs(node.left, val);
dfs(node.right, val);
}
}