题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> a,b,c;
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>> ans;
preOrder(root);
inOrder(root);
postOrder(root);
ans.push_back(a);
ans.push_back(b);
ans.push_back(c);
return ans;
}
void preOrder(TreeNode* root)
{
if(root==NULL) return;
a.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
void inOrder(TreeNode* root)
{
if(root==NULL) return;
inOrder(root->left);
b.push_back(root->val);
inOrder(root->right);
}
void postOrder(TreeNode* root)
{
if(root==NULL) return;
postOrder(root->left);
postOrder(root->right);
c.push_back(root->val);
}
};
查看6道真题和解析