Thursday, September 4, 2014

Binary Tree Traversal without Recursion 2

Morris Traversal

    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> ret;
        TreeNode *cur=root, *prev=NULL;
       
        while(cur!=NULL){
            if (cur->left==NULL){
                ret.push_back(cur->val);
                cur = cur->right;
            }
            else{
                prev = cur->left;
               
                while(prev->right!=NULL && prev->right!=cur)
                prev = prev->right;
               
                if (prev->right==NULL){
                    ret.push_back(cur->val);
                    prev->right = cur;
                    cur = cur->left;
                }
                else{
                    prev->right=NULL;
                    cur = cur->right;
                }
            }
        }
       
        return ret;
    }

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> ret;
        TreeNode *cur=root, *prev=NULL;
       
        while(cur!=NULL){
            if (cur->left==NULL){
                ret.push_back(cur->val);
                cur = cur->right;
            }
            else{
                prev = cur->left;
               
                while(prev->right!=NULL && prev->right!=cur)
                prev = prev->right;
               
                if (prev->right==NULL){
                   
                    prev->right = cur;
                    cur = cur->left;
                }
                else{
                    ret.push_back(cur->val);
                    prev->right=NULL;
                    cur = cur->right;
                }
            }
        }
       
        return ret;       
    }

No comments:

Post a Comment