【刷题之路】二叉树先序序列化

来源:互联网 发布:php网页编辑软件有哪些 编辑:程序博客网 时间:2024/05/01 15:27

将一颗二叉树先序遍历并输出一个字符串,每个数字后加‘!’作为分隔,空节点记为‘#!’

class TreeToString {
public:
    string toString(TreeNode* root) {
        string res;
        string temp;
        stack<TreeNode*> p1;
        TreeNode* cur;
        p1.push(root);
        while(!p1.empty()){   //利用循环先序遍历二叉树
            cur=p1.top();
            p1.pop();
            if(cur==NULL){
                res+="#!"; 
                continue;
            }
            temp=str1(cur->val);  //整型转字符串,可以替换为sprintf函数,功能一样
            temp+='!';
            res+=temp;
            if(cur) p1.push(cur->right);  //即时左右孩子节点为空,依然押入,只有当当前节点为空时停止,与二叉树先序遍历稍有不同
            if(cur) p1.push(cur->left);
            else res+="#!"; 
        }
        return res;
    }
    string str1(int a){
        std::stringstream ss; //字符串流std ,将节点val变为字符串

        ss << a;
return  ss.str();
    }
};

0 0
原创粉丝点击