二叉树的三种遍历(递归实现)
/**
* 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<>>
*/
vector<vector<int> > threeOrders(TreeNode* root) {
vector<vector<int>> vv;
vector<int> one = preOrder(root);
vector<int> two = midOrder(root);
vector<int> three = postOrder(root);
vv.push_back(one);
vv.push_back(two);
vv.push_back(three);
return vv;
}
vector<int> preOrder(TreeNode* root) {
vector<int> v;
if (root == NULL) return v;
v.push_back(root->val);
vector<int> lv = preOrder(root->left);
convert(lv, v);
vector<int> rv = preOrder(root->right);
convert(rv, v);
return v;
}
vector<int> midOrder(TreeNode* root) {
vector<int> v;
if (root == NULL) return v;
vector<int> lv = midOrder(root->left);
convert(lv, v);
v.push_back(root->val);
vector<int> rv = midOrder(root->right);
convert(rv, v);
return v;
}
vector<int> postOrder(TreeNode* root) {
vector<int> v;
if (root == NULL) return v;
vector<int> lv = postOrder(root->left);
convert(lv, v);
vector<int> rv = postOrder(root->right);
convert(rv, v);
v.push_back(root->val);
return v;
}
void convert(vector<int>& a, vector<int>& b) {
for (int i = 0; i < a.size(); i++) {
b.push_back(a[i]);
}
}
};