Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ] -----------------------------------------------------------------------------就是遍历二叉树的的每一层,并且把每一层的数加入到一个数组,返回这个二维数组。 C++代码:
/** * 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) { queue<TreeNode*> q; vector<int> vec; vector<vector<int> > vecs; if(!root){ return vecs; //这个vecs指的是空数组。 } q.push(root); while(!q.empty()){ vec.clear(); for(int i = q.size();i>0;i--){ auto t = q.front(); q.pop(); vec.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } vecs.push_back(vec); } return vecs; } };
原文地址:https://www.cnblogs.com/Weixu-Liu/p/10721261.html
时间: 2024-10-15 11:19:30