剑指Offer-第6天 搜索与回溯算法(简单)


第一题

题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

个人题解:BFS即可

代码:

/**
 * 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 levelOrder(TreeNode* root) {
        vector res;
        if(!root) return {};

        queue q;
        q.push(root);
        while(!q.empty()){
            auto t=q.front(); 
            q.pop();
            res.push_back(t->val);
            if(t->left) q.push(t->left);
            if(t->right) q.push(t->right);
        }

        return res;
    }
};

运行截图:

第二题

题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/

个人题解:开二维数组,每次填入空的一维数组,重复第一题的操作即可。

代码:

/**
 * 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> levelOrder(TreeNode* root) {
        vector> res;
        if(!root) return res;

        queue q;
        q.push(root);
        while(!q.empty())
        {
            int n=q.size();
            res.push_back(vector());
            for(int i=1;i<=n;i++)
            {
                auto t=q.front(); 
                q.pop();
                res.back().push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        return res;
    }
};

运行截图:

第三题

题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

个人题解:设置一个 \(idx\),偶数的时候反转数组即可,其他操作和第二题一样。

代码:

/**
 * 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> levelOrder(TreeNode* root) {
        vector> res;
        if(!root) return res;

        queue q;
        q.push(root); 
        int i=1;
        while(q.size()){
            int len=q.size();
            vector lev;
            for(int j=0;jval);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);                      
            }
            if(i%2==0) reverse(lev.begin(),lev.end());    
            res.push_back(lev);  i++;
        }
        return res;
    }
};

运行截图:

相关