Tree Traversal 总结

本文总结一下几种tree traversal的形式,都是用iterative的方式。而且基本是stack

  1. Preorder traversal
vector preorderTraversal(TreeNode* root) {
        vector ret;
        if(!root){
            return ret;
        }
        
        stack 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;
    }
  1. Inorder Traversal
vector inorderTraversal(TreeNode* root) {
        vector ret;
        if(!root){
            return ret;
        }
        
        stack 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;
    }
  1. Postorder traversal
    Post Order需要建立pre变量
vector postorderTraversal(TreeNode* root) {
        vector ret;
        if(!root){
            return ret;
        }
        
        stack 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;
    }
  1. 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;
                }
            }
        }

你可能感兴趣的:(Tree Traversal 总结)