1 前序遍历
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
if(!root){
return res;
}
stack<TreeNode *> st1;
st1.push(root);
while(!st1.empty()){
TreeNode *node=st1.top();
res.push_back(node->val);
st1.pop();
if(node->right){
st1.push(node->right);
}
if(node->left){
st1.push(node->left);
}
}
return res;
}
};
2 二叉树中顺序遍历
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> ivec;
if(root==NULL){
return ivec;
}
stack<TreeNode *> st;
TreeNode *cur=root;
while(!st.empty()||cur){ //一样判断一个
if(cur){
while(cur){
st.push(cur);
cur=cur->left;
}
}
if(!st.empty()) {
cur=st.top();
st.pop();
ivec.push_back(cur->val);
cur=cur->right;
}
}
return ivec;
}
};
void middle(TreeNode* root,vector<int> &iteration)
{
stack<TreeNode*> store;
TreeNode* current=root;
while(!store.empty()||current!=NULL)
{
if(current!=NULL)
{
store.push(current);
current=current->left;
}
else
{
current=store.top();
iteration.push_back(current->val);
current=current->right;
store.pop();
}
}
}