二叉树递归遍历【前中后序】
(一开始还卡住了。。。。)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
void preorder_traversal(std::vector<int> &preorder, TreeNode *root) {
if (root) {
preorder.push_back(root->val);
preorder_traversal(preorder, root->left);
preorder_traversal(preorder, root->right);
}
}
void inorder_traversal(std::vector<int> &inorder, TreeNode *root) {
if (root) {
inorder_traversal(inorder, root->left);
inorder.push_back(root->val);
inorder_traversal(inorder, root->right);
}
}
void postorder_traversal(std::vector<int> &postorder, TreeNode *root) {
if (root) {
postorder_traversal(postorder, root->left);
postorder_traversal(postorder, root->right);
postorder.push_back(root->val);
}
}
vector<vector<int> > threeOrders(TreeNode* root) {
// 前中后序
std::vector<int> preorder, inorder, postorder;
preorder_traversal(preorder, root);
inorder_traversal(inorder, root);
postorder_traversal(postorder, root);
return std::vector<std::vector<int>>{preorder, inorder, postorder};
}
};