669. Trim a Binary Search Tree
来源:互联网 发布:拓展人脉的软件 编辑:程序博客网 时间:2024/06/06 13:59
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.
Example 1:
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.根节点和子节点的一个是相等的,另外一个可能要大,也可能相等。返回树的次小值
这个题考察递归。关键点是把根节点的值和下面的值进行比较
class Solution {public: int findSecondMinimumValue(TreeNode* root) { if(root==nullptr) return -1; else return minSPoint(root,root->val); } int minSPoint(TreeNode* root,int first){ if(root==nullptr) return -1; if(root->val!=first) return root->val; int left=minSPoint(root->left,first); int right=minSPoint(root->right,first); if(left==-1) return right; if(right==-1) return left; return min(left,right);//如果两个都不是-1,说明两个值都是比first大的,因为如果和first相等,最后一定是到尾部返回-1。 }};
阅读全文
0 0
- leetcode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- LeetCode 669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- leetcode: 669. Trim a Binary Search Tree
- <LeetCode>669. Trim a Binary Search Tree
- leetcode 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- LeetCode 669. Trim a Binary Search Tree
- [LeetCode] 669.Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- 669. Trim a Binary Search Tree
- oracle数据库(二)
- 2017吉林省赛 C题 线段树
- listview方法的调用顺序
- 洛谷 P3040 [USACO12JAN]贝尔分享Bale Share
- 数据结构-线性表的链式存储
- 669. Trim a Binary Search Tree
- Flask学习——数据库迁移
- BZOJ 2081 Beads Hash
- 基础Win32知识
- FastStone Capture 8.4 注册码(转)
- C++中的多态
- mybatis和hibernate的区别
- 剑指offer:按之字形顺序打印二叉树
- 用小说的形式讲解Spring(2) —— 注入方式哪家强