[LeetCode] 102. Hierarchical traversal of binary tree (C + +)

Title address: https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

Title Description:

Given a binary tree, it returns the value of the nodes it traverses hierarchically. (that is, access all nodes layer by layer, from left to right).

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

   / \
  9  20
    /  \
   15   7

Return its hierarchical traversal result:


Use queues for hierarchical traversal:

Because this problem does not only need to traverse hierarchically, and the final results need to be saved hierarchically (that is, each layer of nodes is saved in a vector), so it needs a depth record which is the current layer, a cout record that there are several nodes in this layer, and then use the queue first in first out to traverse all nodes one by one.

 * 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 {
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(root==nullptr)return vector<vector<int>>{};
        queue<TreeNode*> data;
        vector<vector<int>> res;
        int depth=0;
            res.push_back(vector<int> {});//What layer of storage space will be opened up
            int cout = data.size();//What layer has cout nodes
            while(cout--){//Traversal layer
                if(root->left != nullptr)data.push(root->left);
                if(root->right != nullptr)data.push(root->right);
                if(!data.empty())root = data.front();
            depth += 1;//Layer number plus 1
        return res;

Recursive preamble traversal: (refer to leetcode comments)

  • Use the depth variable to record the current layer (starting from 0), and enter the lower layer when depth + 1;
  • If depth > = vector. Size() indicates that this layer has not been used yet, this is the first time, so we need to expand the capacity;
  • Because it's preorder traversal, middle left right. For each layer, the left one must be traversed before the right one. In fact, the order in the subsequent order is the same
class Solution {
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        pre(root, 0, ans);
        return ans;
    void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
        if (!root) return ;//void
        if (depth >= ans.size())
            ans.push_back(vector<int> {});
        pre(root->left, depth + 1, ans);
        pre(root->right, depth + 1, ans);


Posted by Sneo on Sun, 01 Dec 2019 19:28:47 -0800