[LeetCode] Binary Tree Level Order Traversal
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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
问题描述:给定一个二叉树,层次遍历它的所有节点。
class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. if(root == NULL) return vector<vector<int> >(0); queue<pair<TreeNode *, int> > que; vector<vector<int> > vec; vector<int> ivec; TreeNode *pnode = root; int level = 0; pair<TreeNode *, int> pair_data; que.push(make_pair(pnode, 1)); while(!que.empty()) { pair_data = que.front(); que.pop(); pnode = pair_data.first; level = pair_data.second; ivec.push_back(pnode->val); if(que.empty() || level != que.front().second) { vec.push_back(ivec); ivec.clear(); } if(pnode->left) { que.push(make_pair(pnode->left, level+1)); } if(pnode->right) { que.push(make_pair(pnode->right, level+1)); } } return vec; } };
补充:软件开发 , C++ ,