题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
vector<int>pre;
vector<int>mid;
vector<int>post;
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
if(root != NULL)
{
preorder(root);
midorder(root);
postorder(root);
}
vector<vector<int>>res = {pre, mid, post};
return res;
}
void preorder(TreeNode* root)
{
if(root == NULL)return;
pre.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
void midorder(TreeNode* root)
{
if(root == NULL)return;
midorder(root->left);
mid.push_back(root->val);
midorder(root->right);
}
void postorder(TreeNode* root)
{
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
post.push_back(root->val);
}
};



嘉士伯公司氛围 583人发布