一、二叉树的层次遍历、先序、中序、后序遍历
????????C语言这里
C++
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;//保存最后结果
if(root==NULL) return res;
queue<TreeNode *>q;
q.push(root);
while(!q.empty())
{
vector<int> temp;
int n = q.size();
for(int i=0;i<n;++i)
{
TreeNode *node = q.front();
q.pop();
temp.push_back(node->val);
if(node->left != NULL) q.push(node->left);
if(node->right != NULL) q.push(node->right);
}
res.push_back(temp);
}
return res;
}
};
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
vector<int> pre;
vector<int> in;
vector<int> post;
class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
void preOrder(TreeNode *root)
{
if(root!=NULL)
{
pre.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode *root)
{
if(root!=NULL)
{
inOrder(root->left);
in.push_back(root->val);
inOrder(root->right);
}
}
void postOrder(TreeNode *root)
{
if(root!=NULL)
{
postOrder(root->left);
postOrder(root->right);
post.push_back(root->val);
}
}
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>> res;
preOrder(root);
res.push_back(pre);
inOrder(root);
res.push_back(in);
postOrder(root);
res.push_back(post);
return res;
}
};
|