The sword refers to the offer-question 62: Serialize the binary tree

Topic description

Please implement two functions to serialize and deserialize binary trees respectively

Experimental platform: Niuke.com


Solutions:

write picture description here
write picture description here

java:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    int index = -1;
    // 序列化
    String Serialize(TreeNode root) {
        String str = "";
        if (root == null) {
            str = str + '$' + ',';
            return str;
        } else {
            str = str + root.val + ',';
            str = str + Serialize(root.left);
            str = str + Serialize(root.right);
        }
        return str;
    }

    TreeNode Deserialize(String str) {
        TreeNode root = null;
        if (str != null) {
            String[] strArray = str.split(",");
            if (strArray[0] != "$") {
                root = Deserialize(strArray);
            } else {
                return null;
            }
        }
        return root;
    }

    TreeNode Deserialize(String[] strArray) {
        index++;
        TreeNode node = null;
        if (!strArray[index].equals("$")) {
            node = new TreeNode(Integer.parseInt(strArray[index]));
            node.left = Deserialize(strArray);
            node.right = Deserialize(strArray);
        }
        return node;
    }
}

python:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324774162&siteId=291194637