Binary tree: The sequence traversal is here!

After I debut, I will play ten!

Although you cannot hit ten after reading this article, you can hit five quickly! And fast enough!

102. Sequence traversal of binary trees

Give you a binary tree, please return the node value obtained by traversing it in order. (That is, visit all nodes from left to right layer by layer).

Ideas

We have talked about three articles about depth-first traversal of binary trees before:

Next, we will introduce another way of traversing binary trees: layer sequence traversal.

The layer sequence traverses a binary tree. It is to traverse the binary tree layer by layer from left to right. This way of traversal is different from what we have mentioned before.

Need to borrow an auxiliary data structure, the queue to achieve, "The queue is first in, first out, which conforms to the logic of traversal layer by layer, but the logic of stack first in last out is suitable for simulating depth-first traversal, which is recursive."

"And this kind of hierarchy traversal method is breadth-first traversal in graph theory, but we apply it to binary trees."

Use queues to implement breadth-first traversal of binary trees. The animation is as follows:

 

In this way, the layer sequence traverses the binary tree from left to right.

The code is as follows: "This code can also be used as a template for binary tree hierarchy traversal, and it will depend on it if you type four more in the future . "

C++ code

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            // 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
            for (int i = 0; i < size; i++) {
                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);
            }
            result.push_back(vec);
        }
        return result;
    }
};

"At this time, we have mastered the traversal of the binary tree. Then the following four questions on the leetcode, you only need to modify one or two lines of code in the template (no more) to defeat!"

107. Binary Tree Level Traversal II

Given a binary tree, return its node value to traverse from bottom to top. (That is, from the layer where the leaf node is located to the layer where the root node is located, traverse from left to right layer by layer)

Ideas

Compared to 102. Binary tree traversal, it is enough to reverse the result array at the end.

C++ code

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) { 
                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);
            }
            result.push_back(vec);
        }
        reverse(result.begin(), result.end()); // 在这里反转一下数组即可
        return result;

    }
};

199. Right view of binary tree

Given a binary tree, imagine yourself standing on the right side of it, and return the node values ​​that can be seen from the right side in order from top to bottom.

Ideas

When traversing the layer sequence, determine whether to traverse to the last element of the single layer, if so, put it in the result array, and then return the result.

C++ code

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<int> result;
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (i == (size - 1)) result.push_back(node->val); // 将每一层的最后元素放入result数组中
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return result;
    }
};

637. The layer average of the binary tree

Given a non-empty binary tree, return an array consisting of the average value of each level of nodes.

Ideas

This question is to find the sum of one layer and then take an average when traversing the layer sequence.

C++ code

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<double> result;
        while (!que.empty()) {
            int size = que.size();
            double sum = 0; // 统计每一层的和
            for (int i = 0; i < size; i++) { 
                TreeNode* node = que.front();
                que.pop();
                sum += node->val;
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            result.push_back(sum / size); // 将每一层均值放进结果集
        }
        return result;
    }
};

429. N-ary tree traversal

Given an N-ary tree, return the traversal sequence of its node values. (That is, traverse layer by layer from left to right).

For example, given a three-ary tree:

Return its hierarchy traversal:

[
[1],
[3,2,4],
[5,6]
]

Ideas

This question is still a template question, but a node has multiple children

C++ code

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        queue<Node*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) { 
                Node* node = que.front();
                que.pop();
                vec.push_back(node->val);
                for (int i = 0; i < node->children.size(); i++) { // 将节点孩子加入队列
                    if (node->children[i]) que.push(node->children[i]);
                }
            }
            result.push_back(vec);
        }
        return result;

    }
};

to sum up

The sequence traversal of the binary tree is the application of breadth-first search in graph theory in the binary tree. It needs to be implemented with the help of queues (is the application of queues discovered at this time).

Learn to traverse the sequence of binary trees, and you can finish the five questions on leetcode in one go:

  • 102. Sequence traversal of binary trees

  • 107. Binary Tree Level Traversal II

  • 199. Right view of binary tree

  • 637. The layer average of the binary tree

  • Preorder traversal of 589.N fork tree

Although you can't hit ten in one go, five is fine.

If you have to hit ten, you have to find Master Ye!

This article: https://github.com/youngyangyang04/leetcode-master already included, there is also the question Raiders leetcode brush, brush each type classic topic title sequence, mind map, you can fork into their own warehouses , empty look You will definitely gain something, if it helps you, give a star to support it!

My B station (there are algorithm videos and programming related knowledge I explained) : https://space.bilibili.com/525438321

I am Carl, a programmer, and a senior brother of Harbin Engineering. I have been engaged in technology research and development for Tencent and Baidu for many years. I used my spare time to brush leetcode. More exciting algorithm articles are available:  Code Random Thoughts.    After paying attention, reply "Java" "C++" "python" "Resume template" and so on. With the learning materials I have compiled for many years, you can add me to   WeChat , remark "personal profile" + "group review questions", and pull you into the review group (no ads, pure personal sharing), I analyze a classic topic every day. Every topic I choose is not isolated, but from the shallower to the deeper. If you follow the rhythm and read each article continuously, you will definitely be integrated.

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/108875311
Recommended