题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<vector<int> > ans;
void pre(TreeNode* root,vector<int> &temp){
if(root == NULL)
return;
temp.push_back(root->val);
pre(root->left,temp);
pre(root->right,temp);
}
void Mid(TreeNode* root,vector<int> &temp){
if(root == NULL)
return;
Mid(root->left,temp);
temp.push_back(root->val);
Mid(root->right,temp);
}
void End(TreeNode* root,vector<int> &temp){
if(root == NULL)
return;
End(root->left,temp);
End(root->right,temp);
temp.push_back(root->val);
}
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<int> temp;
pre(root,temp);
ans.push_back(temp);
temp.clear();
Mid(root,temp);
ans.push_back(temp);
temp.clear();
End(root,temp);
ans.push_back(temp);
return ans;
}
};