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]
]
这道题利用宽度优先搜索就可以了,具体程序(8ms)如下:
/**
* 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) {
vector<vector<int>> retVec;
if(!root)
return retVec; retVec.push_back(vector<int>{root->val});
queue<TreeNode *> que;
que.push(root);
while(true)
{
vector<int> vec;
queue<TreeNode *> q;
while(!que.empty())
{
TreeNode *tree = que.front();
que.pop();
if(tree->left)
{
vec.push_back((tree->left)->val);
q.push(tree->left);
}
if(tree->right)
{
vec.push_back((tree->right)->val);
q.push(tree->right);
}
} if(!q.empty())
{
que = q;
retVec.push_back(vec);
}
else
break;
} return retVec;
}
};
Binary Tree Level Order Traversal II
题目要求:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
这道题基本更上边的题目一样,我们只需要将上题的结果retVec最后再反转一下就可以了,即添加如下一行即可:
reverse(retVec.begin(), retVec.end());
这样的程序只要8ms,但下边基本一样的程序却要64ms:
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> retVec;
if(!root)
return retVec; retVec.insert(retVec.begin(), vector<int>{root->val});
queue<TreeNode *> que;
que.push(root);
while(true)
{
vector<int> vec;
queue<TreeNode *> q;
while(!que.empty())
{
TreeNode *tree = que.front();
que.pop();
if(tree->left)
{
vec.push_back((tree->left)->val);
q.push(tree->left);
}
if(tree->right)
{
vec.push_back((tree->right)->val);
q.push(tree->right);
}
} if(!q.empty())
{
que = q;
retVec.insert(retVec.begin(), vec);
}
else
break;
} return retVec;
}
};