力扣刷题——二叉树

力扣刷题144 二叉树的前序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*> s;
        TreeNode* p=root;
        while(!s.empty()||p){
            if(p){
                s.push(p);
                v.push_back(p->val);
                p=p->left;
            }
            else{
                p=s.top();
                s.pop();
                p=p->right;
            }
        }
        return v;
    }
};

力扣刷题94 二叉树得中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* p= root;
        vector<int> v;
        while(p||!s.empty()){
            if(p){
                s.push(p);
                p=p->left;
            }
            else{
                p=s.top();
                s.pop();
                v.push_back(p->val);
                p=p->right;
            }
        }
        return v;
    }
};

力扣刷题145二叉树的后序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>v;
        stack<TreeNode*>s;
        TreeNode* p=root;
        TreeNode* r= NULL;
        while(p||!s.empty()){
            if(p){
                s.push(p);
                p=p->left;
            }
            else{
                p=s.top();
                if(p->right&&p->right!=r){
                    p=p->right;
                }
                else{
                    s.pop();
                    v.push_back(p->val);
                    r=p;
                    p=NULL;
                }
            }
        }  
        return v;      
    }
};

力扣刷题102二叉树的层次遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> t;
        queue<TreeNode*> Q;
        int size=0;
        if(root==NULL) return res;
        Q.push(root);
        while(!Q.empty()){
            size = Q.size();
            t.clear();
            for(int i=0;i<size;i++){
                t.push_back(Q.front()->val);
                if(Q.front()->left)  Q.push(Q.front()->left);
                if(Q.front()->right)  Q.push(Q.front()->right);
                Q.pop();
            }
            res.push_back(t);
        }
        return res;
    }
};

力扣刷题107自底向上的层次遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> t;
        queue<TreeNode*> Q;
        int size=0;
        if(root==NULL) return res;
        Q.push(root);
        while(!Q.empty()){
            size = Q.size();
            t.clear();
            for(int i=0;i<size;i++){
                t.push_back(Q.front()->val);
                if(Q.front()->left)  Q.push(Q.front()->left);
                if(Q.front()->right)  Q.push(Q.front()->right);
                Q.pop();
            }
            res.push_back(t);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

力扣刷题199二叉树的右视图

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> t;
        queue<TreeNode*> Q;
        int size=0;
        if(root==NULL) return t;
        Q.push(root);
        while(!Q.empty()){
            size = Q.size();
            for(int i=0;i<size;i++){
                //遇到的是本层最后一个
                if(i==size-1)
                   t.push_back(Q.front()->val);
                if(Q.front()->left)  Q.push(Q.front()->left);
                if(Q.front()->right)  Q.push(Q.front()->right);
                Q.pop();
            }
        }
        return t;
    }
};

力扣刷题637二叉树的层平均值 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> t;
        queue<TreeNode*> Q;
        int size=0;
        long long sum=0;//可能会超过int
        if(root==NULL) return t;
        Q.push(root);
        while(!Q.empty()){
            size = Q.size();
            sum=0;
            for(int i=0;i<size;i++){
                sum+=Q.front()->val;
                if(Q.front()->left)  Q.push(Q.front()->left);
                if(Q.front()->right)  Q.push(Q.front()->right);
                Q.pop();
                
            }
            double av=(double)sum/size;
            t.push_back(av);
        }
        return t;
    }
};

力扣刷题429 N叉树的层次遍历

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<int> t;
        vector<vector<int>> res;
        queue<Node*> Q;
        int size=0;
        if(root==NULL) return res;
        Q.push(root);
        while(!Q.empty()){
            size = Q.size();
            t.clear();
            for(int i=0;i<size;i++){
               Node* node=Q.front();
               Q.pop();
               t.push_back(node->val);
               for(int j=0;j<node->children.size();j++){
                   if(node->children[j]!=NULL) Q.push(node->children[j]);
               }
                
            }
            res.push_back(t);
            
        }
        return res;
    }
};

力扣刷题515在每个树行中找最大值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int> t;
        queue<TreeNode*> Q;
        TreeNode* p=root;
        if(p) Q.push(root);
        while(!Q.empty()){
            int size=Q.size();
            int max_val=INT_MIN;
            for(int i=0;i<size;i++){
                p=Q.front();
                max_val=max(max_val,p->val);
                if(p->left) Q.push(p->left);
                if(p->right) Q.push(p->right);
                Q.pop();
            }
            t.push_back(max_val);
        }
        return t;
    }
};

力扣刷题116

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*>Q;//定义一个队列
        Node* pre,*p;
        int size;
        if(root) Q.push(root);
        while(!Q.empty()){
            size=Q.size();
            for(int i=0;i<size;i++){
                if(i==0){
                    pre=Q.front();
                    p=pre;
                    Q.pop();
                }
                else{
                    p=Q.front();
                    Q.pop();
                    pre->next=p;
                    pre=pre->next;  
                }
                if(p->left) Q.push(p->left);
                if(p->right) Q.push(p->right);
            }
            pre->next = NULL;
        }
        return root;
    }
};

力扣刷题104最大深度

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void maxdpt(TreeNode* root,int &maxdepth,int d){
        if(root){
            maxdpt(root->left,maxdepth,d+1);
            maxdpt(root->right,maxdepth,d+1);
            maxdepth=max(maxdepth,d);
        }
    }
    int maxDepth(TreeNode* root) {
        int maxdepth=0,d=1;
        maxdpt(root,maxdepth,d);
        return maxdepth;
    }
};

力扣刷题111二叉树最小深度

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void mindpt(TreeNode* root,int &mindepth,int d){
        if(root){
            mindpt(root->left,mindepth,d+1);
            mindpt(root->right,mindepth,d+1);
            //需要注意的是,只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子为空则不是最低点
            if(root->left==NULL&&root->right==NULL) mindepth=min(mindepth,d);
        }
    }
    int minDepth(TreeNode* root) {
        if(root==NULL) return 0;
        int mindepth=INT_MAX;
        int d=1;
        mindpt(root,mindepth,d);
        return mindepth;
    }
};

力扣刷题226翻转二叉树

这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历会把某些节点的左右孩子翻转了两次!建议拿纸画一画,就理解了

那么层序遍历可以不可以呢?依然可以的!只要把每一个节点的左右孩子翻转一下的遍历方式都是可

以的!

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        invertTree(root->left);         // 左
        swap(root->left, root->right);  // 中
        invertTree(root->left);        // 右
        return root;
    }
};
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                swap(node->left, node->right); // 节点处理
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return root;
    }
};

力扣刷题101对称二叉树

class Solution {
public:
    bool compare(TreeNode* left, TreeNode* right) {
        // 首先排除空节点的情况
        if (left == NULL && right != NULL) return false;
        else if (left != NULL && right == NULL) return false;
        else if (left == NULL && right == NULL) return true;
        // 排除了空节点,再排除数值不相同的情况
        else if (left->val != right->val) return false;

        // 此时就是:左右节点都不为空,且数值相同的情况
        // 此时才做递归,做下一层的判断
        bool outside = compare(left->left, right->right);   // 左子树:左、 右子树:右
        bool inside = compare(left->right, right->left);    // 左子树:右、 右子树:左
        bool isSame = outside && inside;                    // 左子树:中、 右子树:中 (逻辑处理)
        return isSame;

    }
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;
        return compare(root->left, root->right);
    }
};

力扣刷题110平衡二叉树

 分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。

class Solution {
public:
    int getHeight(TreeNode* node) {
        //空节点
        if(!node) return 0;
        int left = getHeight(node->left);
        if(left==-1) return -1;//往上返回
        int right= getHeight(node->right);
        if(right==-1) return -1;
        return abs(left-right)>1?-1:max(left,right)+1;

    }
    bool isBalanced(TreeNode* root) {
        return getHeight(root)==-1? false:true;
    }
};

力扣刷题257二叉树的所有路径

class Solution {
public:
    void allPath(TreeNode* root,vector<int>& t,vector<string>&path){
        if(!root) return;
        t.push_back(root->val);
        if(!root->left&&!root->right){
            string ss="";
            for(int i=0;i<t.size();i++){
                string s=to_string(t[i]);
                ss+=s;
                if(i!=t.size()-1) {ss+='-';ss+='>';}
            }
            path.push_back(ss);
            
        }
        allPath(root->left,t,path);
        allPath(root->right,t,path);
        t.pop_back();
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> t;
        vector<string> path;
        allPath(root,t,path);
        return path;
    }
};

力扣刷题404左叶子之和

class Solution {
public:
    void add (TreeNode* root,int &sum){
        if(!root) return;
        if(root->left&&!root->left->left&&!root->left->right){
            sum+=root->left->val;
        }
        add(root->left,sum);
        add(root->right,sum);
    }
    int sumOfLeftLeaves(TreeNode* root) {
        int sum=0;
        if(root==nullptr) return 0;
        add(root,sum);
        return sum;
    }
};

力扣刷题112路经总和

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(!root) return false;
        if(!root->left&&!root->right&&targetSum==root->val)  return true;
        return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val);
    }
};

力扣106中序和后序构造二叉树

力扣刷题654最大二叉树

class Solution {
public:
    TreeNode* create(vector<int>nums,int left,int right){
        if(left>right) return nullptr;
        int maxindex=left;
        for(int i=left;i<=right;i++) {
            if(nums[i]>nums[maxindex]) maxindex=i;
        }
        TreeNode* node= new TreeNode(nums[maxindex]);
        node->left=create(nums,left,maxindex-1);
        node->right=create(nums,maxindex+1,right);
        return node;

    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return create(nums,0,nums.size()-1);
    }
};

力扣刷题617合并二叉树

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if(!root1) return root2;
        if(!root2) return root1;
        root1->val+=root2->val;
        root1->left=mergeTrees(root1->left,root2->left);
        root1->right=mergeTrees(root1->right,root2->right);
        return root1;
    }
};

力扣刷题700二叉搜索树中的搜索

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == NULL) return root;
        invertTree(root->left);         // 左
        swap(root->left, root->right);  // 中
        invertTree(root->right);        // 右
        return root;
    }
};

力扣刷题98判断是否是二叉排序树

力扣刷题530二叉搜索树的最小绝对差

class Solution {
public:
    TreeNode* pre;
    void Getmin(TreeNode* p,int &mind){
        if(!p) return ;
        Getmin(p->left,mind);
        if(pre&&mind>abs(p->val-pre->val)) mind=abs(p->val-pre->val);
        pre=p;
        Getmin(p->right,mind);
    }
    int getMinimumDifference(TreeNode* root) {
        int mind=INT_MAX;
        pre=nullptr;
        Getmin(root,mind);
        return mind;
    }
};

力扣刷题501二叉搜索树的众数

class Solution {
public:
    vector<int> res;
    TreeNode* pre;
    int count;
    int maxcount;
    void MyfindMode(TreeNode* root) {
        if(!root) return ;
        MyfindMode(root->left);
        if (pre&&pre->val==root->val) count++;
        else count=1;
        if(count==maxcount){
            res.push_back(root->val);
        }
        else if(count>maxcount){
            maxcount=count;
            res.clear();
            res.push_back(root->val);
        }
        pre=root;
        MyfindMode(root->right);
    }
    vector<int> findMode(TreeNode* root){
        count=0;
        maxcount=0;
        MyfindMode(root);
        return res;
    }
};

力扣刷题236二叉树的最近公共祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
         if(root==NULL||root==p||root==q) return root;
         TreeNode* l=lowestCommonAncestor(root->left,p,q);
         TreeNode* r=lowestCommonAncestor(root->right,p,q);
         if(!l) return r;
         if(!r) return l;
         return root;
    }
};

力扣701二叉搜索树中的插入操作

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(!root) {
            TreeNode* node=new TreeNode(val);
            return node;
        }
        if(root->val>val) root->left = insertIntoBST(root->left,val);
        if(root->val<val) root->right = insertIntoBST(root->right,val);
        return root;
    }
};

力扣刷题450删除搜索二叉树的节点

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
       //递归出口1:没找到
       if(!root) return nullptr;
       //递归出口2:找到
       if(root->val==key) {
           //删除的是叶子
           if(root->left==nullptr&&root->right==nullptr){
               return nullptr;//其实达到了让叶子的父亲的指针指向NULL的效果
           }
           //删除节点左空右不空
           else if(root->left==nullptr&&root->right){
               return root->right;//其实达到了让root的父亲的指针指向root->right的效果
           }
           //删除的节点左不空右空
           else if(root->left&&root->right==nullptr){
               return root->left;//其实达到了让root的父亲的指针指向root->left的效果
           }
           //删除的节点的孩子均不空
           else{
               //首先找到后继
               TreeNode* cur=root->right;
               while(cur->left){
                   cur=cur->left;
               }
               cur->left=root->left;
               //此时的情况属于左为空右不为空
               return root->right;
           }

       }
       //递归逻辑
       //单层递归中传入的是root的左(右)子树,返回的是删除val以后的左(右)子树
       if(key<root->val) root->left =deleteNode(root->left,key);
       if(key>root->val) root->right = deleteNode(root->right,key);
       return root;
    }
};

力扣刷题669修建二叉搜索树

 

lass Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(!root) return nullptr;
        if(root->val<low) return trimBST(root->right,low,high);
        else if(root->val>high) return trimBST(root->left,low,high);
        root->left=trimBST(root->left,low,high);
        root->right=trimBST(root->right,low,high);
        return root;
    }
};

力扣刷题108将有序数组转换为二叉搜索树

 

lass Solution {
public:
//左闭右闭
    TreeNode* func(vector<int>nums,int left,int right){
        //非法区间
        if(left>right) return nullptr;
        //取中间值
        int mid = (left+right)/2;
        TreeNode* root= new TreeNode(nums[mid]);
        root->left=func(nums,left,mid-1);
        root->right=func(nums,mid+1,right);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return func(nums,0,nums.size()-1);
    }
};

力扣刷题538将二叉搜索树转为累加树

lass Solution {
public:
    TreeNode* pre;
    TreeNode* convertBST(TreeNode* &root) {
        if(!root) return nullptr;
        convertBST(root->right);
        if(pre)
           root->val+=pre->val;
        pre=root;
        convertBST(root->left);
        return root;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于力扣刷C++常用操作,我可以给你一些常见的操作和技巧: 1. 使用 STL 容器和算法库:STL(Standard Template Library)是 C++ 标准库中的一个重要组成部分,包含了许多常用的容器和算法。在力扣刷中,使用 STL 可以大大提高代码的效率和可读性。例如,vector 可以用来存储动态数组,sort 可以用来排序等等。 2. 使用 auto 关键字:auto 关键字可以自动推导变量类型,可以减少代码量和提高可读性。例如,auto x = 1; 可以自动推导出 x 的类型为 int。 3. 使用 lambda 表达式:lambda 表达式是 C++11 中引入的一种匿名函数,可以方便地定义一些简单的函数对象。在力扣刷中,使用 lambda 表达式可以简化代码,例如在 sort 函数中自定义比较函数。 4. 使用位运算:位运算是一种高效的运算方式,在力扣刷中经常会用到。例如,左移运算符 << 可以用来计算 2 的幂次方,右移运算符 >> 可以用来除以 2 等等。 5. 使用递归:递归是一种常见的算法思想,在力扣刷中也经常会用到。例如,二叉树的遍历、链表的反转等等。 6. 使用 STL 中的 priority_queue:priority_queue 是 STL 中的一个容器,可以用来实现堆。在力扣刷中,使用 priority_queue 可以方便地实现一些需要维护最大值或最小值的算法。 7. 使用 STL 中的 unordered_map:unordered_map 是 STL 中的一个容器,可以用来实现哈希表。在力扣刷中,使用 unordered_map 可以方便地实现一些需要快速查找和插入的算法。 8. 使用 STL 中的 string:string 是 STL 中的一个容器,可以用来存储字符串。在力扣刷中,使用 string 可以方便地处理字符串相关的问。 9. 注意边界条件:在力扣刷中,边界条件往往是解决问的关键。需要仔细分析目,考虑各种边界情况,避免出现错误。 10. 注意时间复杂度:在力扣刷中,时间复杂度往往是评判代码优劣的重要指标。需要仔细分析算法的时间复杂度,并尽可能优化代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值