二叉树与字符串

二叉树按层遍历

1.针对二叉树的宽度优先遍历
2.宽度优先遍历常使用队列结构
3.面试中,常对换行有所要求
如每打印一层就需要进行回车换行操作再打印下一层:
思路:last:表示正在打印的当前行的最右节点
nlast:表示下一行的最右节点,每次入队列都会更新

struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(){}
};
class TreePrinter{
public:
    vector<vector<int>> printTree(TreeNode *root){
        vector<vector<int>> res;
        vector<int> temp;
        queue<TreeNode*> que;
        que.push(root);
        TreeNode *last = root,*nlast=Null,*now =Null;
        while(!que.empty()){
            now = que.front();
            count<<now->val;
            temp.push_back(now->val);
            if(now->left)
                que.push(now->left);
                nlast=now->left;
            if(now->right)
                que.push(now->right);
                nlast=now->right;
            if(now==last)
                res.push_back(temp);
                temp.clear();
                count<<endl;
                last=nlast;
            que.pop();
        }
    return res;
    }
}

二叉树的序列化和反序列化
1.二叉树->字符串(序列化)
2.字符串->二叉树(反序列化)

序列化方式:
1.先序遍历
遇到空节点 在str 末尾加上“#!”
遇到非空节点,假设节点值3,则加上“3!”
从头节点-左节点-右节点

2.中序遍历
3.后序遍历
4.层序遍历

猜你喜欢

转载自blog.csdn.net/jcsyl_mshot/article/details/80585212