剑指 Offer 37. 序列化二叉树 思路与代码

 

 

 思路:这一个问题需要分两步:

1.序列化:把二叉树变成一个字符串。可以使用层序遍历或者前序遍历。代码选择使用层序遍历,注意null也要加进去,否则无法重构二叉树。

2.反序列化:把字符串分割成数组,使用一个m计算出现了多少个null,计算子节点的时候就-2*m。 另一个思路是使用一个队列。null就直接跳过,数就构建树后 加入队列。

 

如果使用前序遍历,注意把null也遍历进来。在反序列化的时候,使用递归,将字符串变成 存着值得 List,判断 节点为 null就return null。节点不为null  就new一个节点,左右子树递归。最后返回这个节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
  StringBuilder str = new StringBuilder();
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root==null){
            return "";
        }
     Queue<TreeNode> s1 = new LinkedList<>();
     s1.add(root);
     while(s1.size()!=0){
         root=s1.remove();
         if(root==null){
            str.append(null+",");
            continue;
         }
         str.append(root.val+",");
           s1.add(root.left);
            s1.add(root.right);
     }
     return str.toString();
    }
 

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data==null ||data.length()==0){
            return null;
        }
     String[] arr = data.split(",");
     int index = 0;
      int length=arr.length;

      TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
      int sum=0;
         Map<Integer,TreeNode> map = new HashMap<>();
         map.put(0,root);
      while(index<length){
          if("null".equals(arr[index])){
                index++;
                sum++;
              continue;
          }

        if(2*index+1-sum*2<length){
            if(!arr[2*index+1-sum*2].equals("null")){
             TreeNode left = new TreeNode(Integer.parseInt(arr[2*index+1-sum*2]));
             map.put(2*index+1-sum*2,left);
                map.get(index).left=left;
            }
            if(2*index+2-sum*2<length){
                 if(!arr[2*index+2-sum*2].equals("null")){
             TreeNode right = new TreeNode(Integer.parseInt(arr[2*index+2-sum*2]));
             map.put(2*index+2-sum*2,right);
                map.get(index).right=right;
            }
            }
        }
        index++;
      }
      return map.get(0);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
树的存储与遍历: 1.初始化二叉树 ```c++ #include <iostream> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode* createTree() { int val; cin >> val; if (val == -1) { return NULL; } TreeNode* root = new TreeNode(val); root->left = createTree(); root->right = createTree(); return root; } ``` 2.先序遍历二叉树 ```c++ void preOrder(TreeNode* root) { if (root == NULL) { return; } cout << root->val << " "; preOrder(root->left); preOrder(root->right); } ``` 3.中序遍历二叉树 ```c++ void inOrder(TreeNode* root) { if (root == NULL) { return; } inOrder(root->left); cout << root->val << " "; inOrder(root->right); } ``` 4.后序遍历二叉树 ```c++ void postOrder(TreeNode* root) { if (root == NULL) { return; } postOrder(root->left); postOrder(root->right); cout << root->val << " "; } ``` 5.销毁二叉树 ```c++ void destroyTree(TreeNode* root) { if (root == NULL) { return; } destroyTree(root->left); destroyTree(root->right); delete root; } ``` 二叉树的复原: 1.由前序、中序序列确定复原二叉树 ```c++ TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if (preorder.empty() || inorder.empty()) { return NULL; } int rootVal = preorder[0]; TreeNode* root = new TreeNode(rootVal); vector<int>::iterator it = find(inorder.begin(), inorder.end(), rootVal); int leftSize = it - inorder.begin(); vector<int> leftPreorder(preorder.begin() + 1, preorder.begin() + 1 + leftSize); vector<int> leftInorder(inorder.begin(), it); vector<int> rightPreorder(preorder.begin() + 1 + leftSize, preorder.end()); vector<int> rightInorder(it + 1, inorder.end()); root->left = buildTree(leftPreorder, leftInorder); root->right = buildTree(rightPreorder, rightInorder); return root; } ``` 2.由中序、后序序列确定复原二叉树 ```c++ TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if (inorder.empty() || postorder.empty()) { return NULL; } int rootVal = postorder.back(); TreeNode* root = new TreeNode(rootVal); vector<int>::iterator it = find(inorder.begin(), inorder.end(), rootVal); int leftSize = it - inorder.begin(); vector<int> leftInorder(inorder.begin(), it); vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftSize); vector<int> rightInorder(it + 1, inorder.end()); vector<int> rightPostorder(postorder.begin() + leftSize, postorder.end() - 1); root->left = buildTree(leftInorder, leftPostorder); root->right = buildTree(rightInorder, rightPostorder); return root; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值