leetcode 中等题(2)

时间:2023-03-08 18:13:55

50. Pow(x, n) (中等)

    double myPow(double x, int n) {
double ans = ;
unsigned long long p;
if (n < ) {
p = -n;
x = / x;
} else {
p = n;
}
while (p) {
if (p & )
ans *= x;
x *= x;
p >>= ;
}
return ans;
}

96. Unique Binary Search Trees(很快)

 class Solution {
public:
int numTrees(int n) {
long ans=;
for(int i=n+;i<=*n;i++)
ans = i*ans/(i-n);
return ans/(n+);
}
};

94. Binary Tree Inorder Traversal(很快)

 /**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> res;
if(root==NULL) return res;
TreeNode* p=root;
while(!s.empty()||p){
if(p){
s.push(p);
p=p->left;
}
else{
p=s.top();
s.pop();
res.push_back(p->val);
p=p->right;
}
}
return res;
}
};
 /**
* 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:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return res;
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
return res;
}
};
 89. Gray Code(很快)
 class Solution {
public:
vector<int> grayCode(int n) {
int len = << n;
vector<int> res(len,);
for(int i = ;i != len;++i){
res[i] =i ^ (i >> );
}
return res;
}
};