[Sword Finger 32] Print binary tree I, II, III from top to bottom

Print binary tree I: traverse with queue sequence: time O(n), space O(n)

Insert picture description here

Time: It takes O(n) time to traverse the binary tree.
Space: When it is a balanced binary tree, when printing the last layer, there are at most (n+1)/2 nodes, which is O(n) space complexity.
Solution:

  1. Initialize the queue and insert the root node
  2. Dequeue, insert the value of the current node into the array, if the left tree of the node is not empty, then join the team, and if the right tree is not empty, then join the team
/**
 * 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<int> levelOrder(TreeNode* root) 
    {
    
    
        // 层序遍历:借助队列
        vector<int> res;
        if (root == nullptr)
            return res;
        queue<TreeNode*> que;
        que.push(root);
        while (!que.empty())
        {
    
    
            TreeNode* node = que.front();
            que.pop();
            res.push_back(node->val);
            if (node->left)
                que.push(node->left);
            if (node->right)
                que.push(node->right);
        }
        return res;
    }
};

Print Binary Tree II: With the help of queues and record the number of each time: time O(n), space O(n)

Insert picture description here
Time: It takes O(n) time to traverse the binary tree.
Space: When it is a balanced binary tree, when printing the last layer, there are at most (n+1)/2 nodes, which is O(n) space complexity.
Solution:

  1. Initialize the queue and insert the root node
  2. Dequeue, insert the value of the current node into the array, if the left tree of the node is not empty, then join the team, and if the right tree is not empty, then join the team
/**
 * 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>> ans;
        if (root == nullptr)
            return ans;
       queue<TreeNode*> que;
       que.push(root);
       while (!que.empty())
       {
    
    
           int n = que.size();
           vector<int> vec;
           while (n--)
           {
    
    
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left)
                    que.push(node->left);
                if (node->right)
                    que.push(node->right);
           }
           ans.push_back(vec);
       }
       return ans;
    }
};

Print Binary Tree III:

Method 1: Dequeue printing two layers at a time, time O(n), space O(n)

Time: It takes O(n) time to traverse the binary tree.
Space: When it is a balanced binary tree, when printing the last layer, there are at most (n+1)/2 nodes, which is O(n) space complexity

answer:

  1. Using the characteristics of deque, print two layers of elements in one loop
  2. Even-numbered layer: The left end of the deque is dequeued and the right end is inserted. Insert the left tree of each node first, then insert the right tree
  3. Odd-numbered layer: the deque is dequeued at the right end and inserted at the left end. Insert the right tree of each node first and then the left tree
    Insert picture description here
/**
 * 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) 
    {
    
    
        // 1.双端队列,一次性打印两层数据
        vector<vector<int>> ans;
        if (root == nullptr)
            return ans;
        deque<TreeNode*> que;
        que.push_back(root);
        while (!que.empty())
        {
    
    
            vector<int> vec;
            int n = que.size();
            while (n--)         			// 打印偶数层,从前出队列,并且插入队列末尾
            {
    
    
                TreeNode* node = que.front();
                que.pop_front();
                vec.push_back(node->val);
                if (node->left)
                    que.push_back(node->left);		// 先插左树再插右树
                if (node->right)
                    que.push_back(node->right);
            }
            ans.push_back(vec);
            if (que.empty())
                break;
            n = que.size();
            vec.clear();
            while (n--)        				 // 打印奇数层,从后出队列,并且插入队列首部
            {
    
    
                TreeNode* node = que.back();
                que.pop_back();
                vec.push_back(node->val);
                if (node->right)
                    que.push_front(node->right);	// 先插右树再插左树
                if (node->left)
                    que.push_front(node->left);
            }
            ans.push_back(vec);
        }
        return ans;
    }
};

Method 2: Queue, reverse the odd layer

answer:

  1. The queue operation is the same as the second question, a new flag bit is added, when an odd bit is encountered, the array is reversed
/**
 * 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) 
    {
    
    
        // 2.普通队列,如果是奇数层则进行反转数据
        vector<vector<int>> ans;
        if (root == nullptr)
            return ans;
        queue<TreeNode*> que;
        que.push(root);
        int flag = 0;		// 标志位
        while (!que.empty())
        {
    
    
            int n = que.size();
            vector<int> vec;
            while (n--)
            {
    
    
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left)
                    que.push(node->left);
                if (node->right)
                    que.push(node->right);
            }
            if (flag)		// 如果时奇数层则反转数组
                reverse(vec.begin(), vec.end());
            flag ^= 1;
            ans.push_back(vec);
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113883666