题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入
{1,2,3}
返回值
[[1,2,3],[2,1,3],[2,3,1]]
题解:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
private:
vector<int> pre,mid,post;
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>> res;
if(root == nullptr) return res;
//vector<int> pre,mid,post;
preOrder(root);
midOrder(root);
postOrder(root);
res = {pre,mid,post};
return res;
}
void preOrder(TreeNode* rot)
{
if(rot == nullptr) return;
pre.push_back(rot->val);
preOrder(rot->left);
preOrder(rot->right);
}
void midOrder(TreeNode* rot)
{
if(rot == nullptr) return;
midOrder(rot->left);
mid.push_back(rot->val);
midOrder(rot->right);
}
void postOrder(TreeNode* rot)
{
if(rot == nullptr) return;
postOrder(rot->left);
postOrder(rot->right);
post.push_back(rot->val);
}
};