leetcode 107 binary tree hierarchy traversal II

Binary tree? Traverse the level!

Title:
Given a binary tree, the node returns its bottom-up value hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

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

Topic analysis

  • Goal: traverse the level from the bottom up +

Ideas
for each layer ==> Save this layer with a queue node
for a point in the queue ==> read node value + the child node in a queue

Problem-solving ideas

variable effect
q Save Node queue
years Save traverse the level of results

process

Root node in the queue

When the queue is not empty

  1. For controlling the number of cycles for each layer by
  2. Reading the first node value
  3. The first node from the team
  4. Child node into the team
  5. End for loop ==> one traversed node inserted ans foremost

code show as below

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if(!root) return {};
        queue<TreeNode*> q{{root}};
        vector<vector<int>> ans;
        while(!q.empty())
        {
            vector<int> one;
            for (int i = q.size(); i > 0; i--){         //控制一层的结点个数
                TreeNode *t = q.front();
                q.pop();
                one.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            ans.insert(ans.begin(),one);           //插入到结果最前面
        }
        return ans;
    }
};
Published 34 original articles · won praise 0 · Views 569

Guess you like

Origin blog.csdn.net/Luyoom/article/details/104981809