31天剑指offer (6/31)搜索与回溯算法

剑指 Offer 32 - I. 从上到下打印二叉树

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

在这里插入图片描述

/**
 * 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:
    queue<TreeNode*> q;
    vector<int> levelOrder(TreeNode* root) {
    
    
          vector<int> res;
        if(root==NULL) return res;   
        q.push(root);
        while(!q.empty())
        {
    
    
            TreeNode* cur = q.front();
            q.pop();
            res.push_back(cur->val);
            if(cur->left!=NULL) q.push(cur->left);
            if(cur->right!=NULL) q.push(cur->right);
        }
        return res;

    }
};

剑指 Offer 32 - II. 从上到下打印二叉树 II

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

在这里插入图片描述
注意:
1.判断是否为空树
2.for循环内的第二个不能写成q.size().

/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
    
    
    vector<vector<int>> res;
    queue<TreeNode*> q;
    if(root==NULL) return res;
    q.push(root);
    while(!q.empty())
    {
    
    
        vector<int> row;
        int k = q.size();
        for(int i = 0;i < k;i++)
        {
    
         
            TreeNode* cur = q.front();
            q.pop();
            row.push_back(cur->val);
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
        }
        res.push_back(row);
    }
    return res;


    }
};

剑指 Offer 32 - III. 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

在这里插入图片描述
只是在上一题的基础上加个判断就行

/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
    
    
    vector<vector<int>> res;
    queue<TreeNode*> q;
    if(root==NULL) return res;
    q.push(root);
    int ac = 1;
    while(!q.empty())
    {
    
    
        vector<int> row;
        int k = q.size();
        for(int i = 0;i < k;i++)
        {
    
         
            TreeNode* cur = q.front();
            q.pop();
            row.push_back(cur->val);
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
        }
        ac++;
        if(ac%2==1) reverse(row.begin(),row.end()); 
        res.push_back(row);
    }
    return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_47997583/article/details/121335425
今日推荐