leetcode 中等题(2)

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

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

 96. Unique Binary Search Trees(很快)

1 class Solution {
2 public:
3     int numTrees(int n) {
4         long ans=1;
5         for(int i=n+1;i<=2*n;i++)
6             ans = i*ans/(i-n);
7         return ans/(n+1);
8     }
9 };
View Code

 94. Binary Tree Inorder Traversal(很快)

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode* root) {
13         stack<TreeNode*> s;
14         vector<int> res;
15         if(root==NULL) return res;
16         TreeNode* p=root;
17         while(!s.empty()||p){
18             if(p){
19                 s.push(p);
20                 p=p->left;
21             }
22             else{
23                 p=s.top();
24                 s.pop();
25                 res.push_back(p->val);
26                 p=p->right;
27             }
28         }
29         return res;
30     }
31 };
View Code
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> res;
13     vector<int> inorderTraversal(TreeNode* root) {
14         if(!root) return  res;
15         inorderTraversal(root->left);
16         res.push_back(root->val);
17         inorderTraversal(root->right);
18         return res;
19     }
20 };
View Code
 89. Gray Code(很快)
 1 class Solution {
 2 public:
 3     vector<int> grayCode(int n) {
 4         int  len = 1 << n;
 5         vector<int> res(len,0);
 6         for(int i = 0;i != len;++i){
 7             res[i] =i ^ (i >> 1); 
 8         }
 9         return res;
10     }
11 };
View Code

 

转载于:https://www.cnblogs.com/zpcoding/p/10205578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值