本文总结一下几种tree traversal的形式,都是用iterative的方式。而且基本是stack
- Preorder traversal
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root){
return ret;
}
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *cur = st.top(); st.pop();
ret.push_back(cur->val);
if(cur->right){
st.push(cur->right);
}
if(cur->left){
st.push(cur->left);
}
}
return ret;
}
- Inorder Traversal
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root){
return ret;
}
stack<TreeNode*> st;
TreeNode *cur = root;
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur = cur->left;
}
else{
TreeNode *node = st.top(); st.pop();
ret.push_back(node->val);
cur = node->right;
}
}
return ret;
}
- Postorder traversal
Post Order需要建立pre变量
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root){
return ret;
}
stack<TreeNode*> st;
TreeNode *cur = root, *pre = NULL;
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur = cur->left;
}
else{
TreeNode *node = st.top();
if(!node->right || node->right == pre){
st.pop();
ret.push_back(node->val);
pre = node;
}
else{
cur = node->right;
}
}
}
return ret;
}
- Morris Traversal (inorder)
while(node != NULL){
if(!node->left){
process(node);
node = node->right;
}
else{
TreeNode *pre = node->left;
while(pre->right && pre->right != node){
pre = pre->right;
}
if(pre->right == NULL){
pre->right = node;
node = node->left;
}
else{
pre->right = NULL;
process(node);
node = node->right;
}
}
}
网友评论