LeetCode 107. Hierarchical traversal of binary tree II (queue)

1. Title

Given a binary tree, return the traversal of its node values ​​from bottom to top.
(That is, from the layer where the leaf node is located to the layer where the root node is located, traversing from left to right layer by layer)

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

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

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

2. Problem solving

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if(root == NULL)
        	return {};
        queue<TreeNode*> q;
        vector<int> lv;
        vector<vector<int>> ans;
        q.push(root);
        int n;
        while(!q.empty())
        {
        	n = q.size();
            lv.clear();
        	while(n--)
        	{
        		root = q.front();
        		if(root->left)
        			q.push(root->left);
        		if(root->right)
        			q.push(root->right);
        		lv.push_back(root->val);
        		q.pop();
        	}
        	ans.push_back(lv);
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

12 ms 13.7 MB

Published 872 original articles · Like 2479 · Visits 450,000+

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105596834