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
复制代码

 

posted on   爱笑的张飞  阅读(115)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示