void preoder (treenode *root) {
stack<treenode*> st;
st.push(root);
treenode* node;
while (node != NULL || !st.empty()) {
if (node != NULL) {
printf(node->val);
st.push(node);
node = node->left;
} else {
node = st.top();
st.pop();
node = node->right;
}
}
}
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> ans;
ans.clear();
while (root != NULL || !st.empty()) {
if (root != NULL) {
st.push(root);
root = root->left;
} else {
root = st.top();
st.pop();
ans.push_back(root->val);
root = root->right;
}
}
return ans;
}
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> ans;
ans.clear();
TreeNode* tmp;
tmp = NULL;
while (root != NULL || !st.empty()) {
if (root != NULL) {
st.push(root);
root = root->left;
} else {
root = st.top();
st.pop();
if (root->right == NULL || root->right == tmp) {
// root是叶子 || 刚刚是从右边返回来的
ans.push_back(root->val);
tmp = root;
root = NULL;
} else {
// 刚刚是从左边返回来的
st.push(root);
root = root->right;
}
}
}
return ans;
}