C++, use stack and set, no recursion


  • 0
    F
    class Solution {
    public:
        string tree2str(TreeNode* t){
            string s = "";
            if(t==NULL) return s;
            set<TreeNode*> visited_node;
            stack<TreeNode*> stack_node;
            stack_node.push(t);
            while(!stack_node.empty()){
                t = stack_node.top();
                if(visited_node.find(t)==visited_node.end()){
                    s=s + "(" + to_string(t->val);
                    visited_node.insert(t);
                    if(t->right!=NULL) stack_node.push(t->right);
                    if(t->left != NULL) stack_node.push(t->left);
                    if(t->left == NULL && t->right!=NULL){
                        s+="()";
                    } 
                }
                else{
                    s+=")";
                    stack_node.pop();
                }
            }
            s.erase(s.begin()+0);
            s.erase(s.end()-1);
            return s;
        }
    };
    

Log in to reply
 

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