每日一刷
二叉树
实现二叉树先序,中序和后序遍历
一、题目描述
二、解题步骤
/**
* 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 firstOrder(vector<int> &res1, TreeNode* root) {
if (root != NULL) {
res1.push_back(root->val);
firstOrder(res1, root->left);
firstOrder(res1, root->right);
}
}
void secondOrder(vector<int> &res2, TreeNode* root) {
if (root != NULL) {
secondOrder(res2, root->left);
res2.push_back(root->val);
secondOrder(res2, root->right);
}
}
void thirdOrder(vector<int> &res3, TreeNode* root) {
if (root != NULL) {
thirdOrder(res3, root->left);
thirdOrder(res3, root->right);
res3.push_back(root->val);
}
}
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>> res;
vector<int> res1;
firstOrder(res1, root);
res.push_back(res1);
vector<int> res2;
secondOrder(res2, root);
res.push_back(res2);
vector<int> res3;
thirdOrder(res3, root);
res.push_back(res3);
return res;
}
};