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

This commit is contained in:
huangge1199@hotmail.com 2021-07-27 21:52:50 +08:00
parent 4ca840ca8d
commit 6e631a0604
3 changed files with 128 additions and 1 deletions

View File

@ -0,0 +1,93 @@
//给定一个非空特殊的二叉树每个节点都是正数并且每个节点的子节点数量只能为 2 0如果一个节点有两个子节点的话那么该节点的值等于两个子节点中较小的一
//
//
// 更正式地说root.val = min(root.left.val, root.right.val) 总成立
//
// 给出这样的一个二叉树你需要输出所有节点中的第二小的值如果第二小的值不存在的话输出 -1
//
//
//
// 示例 1
//
//
//输入root = [2,2,5,null,null,5,7]
//输出5
//解释最小的值是 2 第二小的值是 5
//
//
// 示例 2
//
//
//输入root = [2,2,2]
//输出-1
//解释最小的值是 2, 但是不存在第二小的值
//
//
//
//
// 提示
//
//
// 树中节点数目在范围 [1, 25]
// 1 <= Node.val <= 231 - 1
// 对于树中每个节点 root.val == min(root.left.val, root.right.val)
//
// Related Topics 深度优先搜索 二叉树
// 👍 198 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
//671:二叉树中第二小的节点
class SecondMinimumNodeInABinaryTree {
public static void main(String[] args) {
//测试代码
Solution solution = new SecondMinimumNodeInABinaryTree().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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;
int val;
public int findSecondMinimumValue(TreeNode root) {
val = root.val;
dfs(root);
return min;
}
public void dfs(TreeNode node) {
if (node == null) {
return;
}
if (min != -1 && node.val >= min) {
return;
}
if (node.val > val) {
min = node.val;
}
dfs(node.left);
dfs(node.right);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,34 @@
<p>给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 <code>2</code> 或 <code>0</code>。如果一个节点有两个子节点的话,那么该节点的值等于两个子节点中较小的一个。</p>
<p>更正式地说,<code>root.val = min(root.left.val, root.right.val)</code> 总成立。</p>
<p>给出这样的一个二叉树,你需要输出所有节点中的<strong>第二小的值。</strong>如果第二小的值不存在的话,输出 -1 <strong></strong></p>
<p> </p>
<p><strong>示例 1</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" style="width: 431px; height: 302px;" />
<pre>
<strong>输入:</strong>root = [2,2,5,null,null,5,7]
<strong>输出:</strong>5
<strong>解释:</strong>最小的值是 2 ,第二小的值是 5 。
</pre>
<p><strong>示例 2</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" style="width: 321px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [2,2,2]
<strong>输出:</strong>-1
<strong>解释:</strong>最小的值是 2, 但是不存在第二小的值。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目在范围 <code>[1, 25]</code></li>
<li><code>1 <= Node.val <= 2<sup>31</sup> - 1</code></li>
<li>对于树中每个节点 <code>root.val == min(root.left.val, root.right.val)</code></li>
</ul>
<div><div>Related Topics</div><div><li></li><li>深度优先搜索</li><li>二叉树</li></div></div>\n<div><li>👍 198</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long