Second Minimum Node In a Binary Tree问题及解法
来源:互联网 发布:华师网络教育平台 编辑:程序博客网 时间:2024/06/05 00:46
问题描述:
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two
or zero
sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
示例:
Input: 2 / \ 2 5 / \ 5 7Output: 5Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: 2 / \ 2 2Output: -1Explanation: The smallest value is 2, but there isn't any second smallest value.
问题分析:
利用DFS寻找树中第二小的值。
过程详见代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int findSecondMinimumValue(TreeNode* root) {int second = -1;bl(root, root->val, second);return second;}void bl(TreeNode* root, int first,int& second){if (root == nullptr) return;if (root->val > first && (root->val < second || second == -1)){second = root->val;}bl(root->left, first, second);bl(root->right, first, second);}};
阅读全文
0 0
- Second Minimum Node In a Binary Tree问题及解法
- 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- Leetcode671. Second Minimum Node In a Binary Tree
- LeetCode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- [LeetCode] Second Minimum Node In a Binary Tree
- LeetCode#671 Second Minimum Node In a Binary Tree (week13)
- 671. Second Minimum Node In a Binary Tree
- LeetCode671. Second Minimum Node In a Binary Tree
- Second Minimum Node In a Binary Tree:求二叉树第二小的值
- 初学java Stream以及Lambda表达式" -> "
- 最新企业管理软件发展趋势分析
- Token ,Cookie和Session的区别
- zxing安卓项目学习1——CaptureActivity之onCreate——BeepManager
- [Leetcode] 391. Perfect Rectangle 解题报告
- Second Minimum Node In a Binary Tree问题及解法
- 将应用的log4j换成logback
- Windows下运行C语言版Word2Vec训练词向量
- Activiti进阶(十)——分配个人任务的三种方式
- 刚做了一个开源工具:使用UI来管理Linux和Unix机器--SSHConnector
- 669. Trim a Binary Search Tree
- 实现发送post和get请求
- linux下配置ip地址四种方法
- java基本数据类型的相互转换