C++ post order traverse solution


  • 0
    L
      vector<string> binaryTreePaths(TreeNode* root) {
            TreeNode*  p=root;
            list<TreeNode *> s;
            TreeNode * last=NULL;
            string path="";
            vector<string> ret;
            list<TreeNode *>::iterator it;
             while(root!=NULL){
                    s.push_back(root);
                    root=root->left;
                }
            while(!s.empty()){
                root=s.back();s.pop_back();
                if(root->right!=NULL&&root->right!=last){
                    s.push_back(root);
                    root=root->right;
                    while(root!=NULL){
                        s.push_back(root);
                        root=root->left;
                    }
                }else {
                    if(root->right==NULL&&root->left==NULL){
                        path="";
                        it=s.begin();
                        while(it!=s.end()){
                         path+=to_string((*it)->val);
                         path+="->";
                         ++it;
                        }
                        path+=to_string(root->val);
                        ret.push_back(path);
                    }
                    last=root;
                }
                
            }
            
            return ret;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.