丑数
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index <= 6) return index;
vector<int> res(index);
res[0]=1;
int t2=0,t3=0,t5=0;
for(int i=1;i<index;i++){
res[i]=min(res[t2]*2,min(res[t3]*3,res[t5]*5));
if(res[i]==res[t2]*2) t2++;
if(res[i]==res[t3]*3) t3++;
if(res[i]==res[t5]*5) t5++;
}
return res[index-1];
}
};
98. 验证二叉搜索树
难度中等523收藏分享切换为英文关注反馈
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入: 2 / \ 1 3 输出: true
示例 2:
输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。
- 中序遍历
- 递归
/**
* 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:
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
stack<TreeNode*> st;
int tag=0,last=0;
while(!st.empty()||root){
while(root){
st.push(root);
root=root->left;
}
TreeNode *tmp=st.top();
st.pop();
if(tag==0){
last=tmp->val;
tag=1;
}else{
if(tmp->val<=last) return false;
else last=tmp->val;
}
if(tmp->right) root=tmp->right;
}
return true;
}
};
class Solution {
public:
bool helper(TreeNode *root,long long int lower,long long int upper ){
//考虑以root为根的子树,节点值是否在lower和upper之间
if(root==NULL) return true;
if(root->val<=lower || root->val>=upper) return false;
return helper(root->left,lower,root->val) && helper(root->right,root->val,upper);
}
bool isValidBST(TreeNode* root) {
return helper(root,LONG_MIN,LONG_MAX);
}
};