2021-11-04 swipe questions and punch in every day

Keywords: C++ Algorithm

2021-11-04 swipe questions and punch in every day

Force buckle - binary tree

102. Sequence traversal of binary tree and Sword finger Offer 32 - II. Print binary tree II from top to bottom

To give you a binary tree, please return the node values obtained by traversing in sequence. (that is, access all nodes from left to right layer by layer).

Example:
Binary tree: [3,9,20,null,null,15,7],

3

/
9 20
/
15 7
Return its sequence traversal result:

[
[3],
[9,20],
[15,7]
]

Sequence traversal is well understood as traversal layer by layer.

The first method - recursion: first prepare a global vector < vector < int > > container V to store the structure. In the function, first judge whether the root is empty. If it is empty, directly return the empty v. if it is not empty, pass the root into dfs and pass a layer number U. in order to comply with the storage mode of the array, we start from 0. In dfs, first judge whether the root is empty. If it is empty, directly end the program. If it is not empty, judge whether the size of the current V is less than u+1. If it is less than u+1, we create a vector container and insert it into V, and then we use v[u].push_back() to insert the val value of the current root, and then send the left and right of the root into the next dfs recursion respectively. At this time, the number of layers we pass is u+1. When all recursion ends, return v.

/**
 * 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>>v;
    vector<vector<int>> levelOrder(TreeNode* root) {   
        if(!root)return v;
        vector<int>v1;
        v.assign(1, v1);
        dfs(root,0);
        return v;
    }
    void dfs(TreeNode* root, int u)
    {
        if (!root)return;
        else
        {
            if(v.size()<u+1)
            {
                vector<int>v1;
                v.push_back(v1);
            }
            v[u].push_back(root->val);
            dfs(root->left, u + 1);
            dfs(root->right, u + 1);
        }
    }
};

The second method - iteration: because the iteration is carried out in a function, you can set the global function vector < vector < int > > V at the beginning of the function. Of course, you can also continue the global function. First judge whether the root is empty. If it is empty, return the empty v to it. If it is not empty, we first prepare a queue container que to store the nodes. First store the root in que, and then start the while traversal. As long as que is not empty, we will traverse all the time. Each traversal takes a number len and stores the size of Que. Len is the number of nodes in the current layer, which also determines the number of for loops below, Then prepare a vector container v1 to store the val value of this layer of nodes, and then start the for loop. The loop is len times. First store the val value of the head node of the current queue in v1, then store the left and right child nodes of the queue head node in que, and then take the team head element out of the queue. After for, insert v1 into v. After all traversal, return v.

/**
 * 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>>v;
        if(!root)return v;
        queue<TreeNode*>que;
        que.push(root);
        while(que.size())
        {
            int len=que.size();
            vector<int>v1;
            for(int i=0;i<len;i++)
            {
                v1.push_back(que.front()->val);
                if(que.front()->left)que.push(que.front()->left);
                if(que.front()->right)que.push(que.front()->right);
                que.pop();
            }
            v.push_back(v1);
        }
        return v;
    }
};

637. Layer average of binary tree

Given a non empty binary tree, return an array composed of the average value of nodes in each layer.

Example 1:

Input:
3
/
9 20
/
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of layer 0 is 3, layer 1 is 14.5 and layer 2 is 11. Therefore, it returns [3, 14.5, 11].

Through the above sequence traversal method, first obtain the number of nodes of each layer, and then calculate the average value normally.

/**
 * 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>>v;
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double>nums;
        if(!root)return nums;
        dfs(root,0);
        double sum=0;
        int n=v.size();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<v[i].size();j++)
            {
                sum+=v[i][j];
            }
            nums.push_back(sum/v[i].size());
            sum=0;
        }
        return nums;
    }
    void dfs(TreeNode* root,int u)
    {
        if(!root)return;
        else
        {
            if(v.size()<u+1)
            {
                vector<int>v1;
                v.push_back(v1);
            }
            v[u].push_back(root->val);
            dfs(root->left,u+1);
            dfs(root->right,u+1);
        }
    }
};

103. Zigzag sequence traversal of binary tree

Given a binary tree, return the sawtooth sequence traversal of its node value. (that is, traverse the next layer from left to right, and then from right to left, and so on, alternating between layers).

For example:
Given binary tree [3,9,20,null,null,15,7],

​ 3

/
9 20
/
15 7
The zigzag sequence traversal is returned as follows:

[
[3],
[20,9],
[15,7]
]

Use the above method of sequence traversal to calculate the number of nodes in each layer, and then change all nodes in odd layers to reverse order (chicken stealing method)

/**
 * 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>>v;
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root)return v;
        dfs(root,0);
        int n=v.size();
        for(int i=1;i<n;i+=2)
        {
            int m=v[i].size();
            int k=m-1;
            for(int j=0;j<m/2;j++)
            {
                swap(v[i][j],v[i][k]);
                k--;
            }
        }
        return v;
    }
    void dfs(TreeNode* root, int u)
    {
        if (!root)return;
        if (v.size() < u + 1)
        {
            vector<int>v1;
            v.push_back(v1);
        }
        v[u].push_back(root->val);
        dfs(root->left, u + 1);
        dfs(root->right, u + 1);
    }
};

Sword finger Offer II 045. Lowest leftmost value of binary tree and 513. Find the value in the lower left corner of the tree

Given the root node root of a binary tree, please find the value of the lowest and leftmost node of the binary tree.

Suppose there is at least one node in the binary tree.

Example 1:

Input: root = [2,1,3]
Output: 1

Use the above sequence traversal method to calculate the number of nodes in each layer, and then return to the first number of the last layer.

/**
 * 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>>v;
    int findBottomLeftValue(TreeNode* root) {
        if(!root)return NULL;
        dfs(root,0);
        int n=v.size()-1;
        return v[n][0];
    }
    void dfs(TreeNode*root,int u)
    {
        if(!root)return;
        if(v.size()<u+1)
        {
            vector<int>v1;
            v.push_back(v1);
        }
        v[u].push_back(root->val);
        dfs(root->left,u+1);
        dfs(root->right,u+1);
    }
};

A simpler method: use a queue container que to store nodes and prepare a number num_left to store the leftmost number of each layer. First store the root in que, and then start the while loop. As long as there are elements in que, continue the loop. First assign the val value of the header element of the current queue to num_left, because the queue head element is the leftmost node of each layer, and then prepare a value len to store the number of nodes in the current queue, which represents the number of nodes in this layer and the end condition of the following for loop. Then enter the for loop, transfer the left and right child nodes of the current team head element into the queue each time, and then pop up the team head element (at this time, the previous len function is reflected. Cycle len times, and pop up the team head element each time, so that after the loop, all the nodes of the upper layer disappear, and the nodes of the next layer are replaced, and the team head element is the leftmost node). When while is finished, Num is returned_ left.

/**
 * 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:
    int findBottomLeftValue(TreeNode* root) {
        if(!root)return NULL;
        queue<TreeNode*>que;
        int num_left;
        que.push(root);
        while(que.size())
        {
            int len=que.size();
            num_left=que.front()->val;
            for(int i=0;i<len;i++)
            {
                if(que.front()->left)que.push(que.front()->left);
                if(que.front()->right)que.push(que.front()->right);
                que.pop();
            }
        }
        return num_left;
    }
};

Posted by juschillinnow on Wed, 03 Nov 2021 23:38:50 -0700