国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專(zhuān)欄INFORMATION COLUMN

[LintCode/LeetCode] Binary Tree Serialization

keithyau / 3464人閱讀

摘要:這里要注意的是的用法。所以記住,用可以從自動(dòng)分離出數(shù)組。跳過(guò)第一個(gè)元素并放入數(shù)組最快捷語(yǔ)句建立的用意記錄處理過(guò)的結(jié)點(diǎn)并按處理所有結(jié)點(diǎn)和自己的連接下面先通過(guò)判斷,再修改的符號(hào)的順序,十分巧妙更輕便的解法

Problem

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called "serialization" and reading back from the file to reconstruct the exact same binary tree is "deserialization".

There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7} denote the following structure:

  3
 / 
9  20
  /  
 15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.

Note
String[] vals = data.substring(1, data.length() - 1).split(",");  

這里要注意的是split()的用法。所以記住,用split()可以從String自動(dòng)分離出數(shù)組。

.substring(beginIndex, endIndex) 

beginIndex(Inclusive), endIndex(exclusive). So, the "{" and "}" are not included in vals[].

Solution
class Solution {

    public String serialize(TreeNode root) {
        if (root == null) {
            return "{}";
        }
        ArrayList queue = new ArrayList();
        queue.add(root);
        for (int i = 0; i < queue.size(); i++) {
            TreeNode node = queue.get(i);
            if (node == null) {
                continue;
            }
            queue.add(node.left);
            queue.add(node.right);
        }
        
        //Of course we can delete this.
        /*
        while (queue.get(queue.size() - 1) == null) {
            queue.remove(queue.size() - 1);
        }
        */
        
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(queue.get(0).val);//remember to add .val
        for (int i = 1; i < queue.size(); i++) {
            if (queue.get(i) == null) {
                sb.append(",#");
            } else {
                sb.append(",");
                sb.append(queue.get(i).val);
            }
        }
        sb.append("}");
        return sb.toString(); //sb is not String, we have to transform
    }

    public TreeNode deserialize(String data) { //more tricky!
        if (data.equals("{}")) {
            return null;
        }
        
        //跳過(guò)data第一個(gè)元素并放入String數(shù)組最快捷語(yǔ)句
        String[] vals = data.substring(1, data.length() - 1).split(",");
        
        //建立ArrayList的用意:記錄處理過(guò)的結(jié)點(diǎn)
        //并按index處理所有結(jié)點(diǎn):和自己的children連接
        ArrayList queue = new ArrayList();
        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
        queue.add(root);
        int index = 0;
        boolean isLeftChild = true;
        for (int i = 1; i < vals.length; i++) {
            if (!vals[i].equals("#")) {
                //vals[i] is a String, so use parseInt()
                TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
                if (isLeftChild) {
                    queue.get(index).left = node;
                } else {
                    queue.get(index).right = node;
                }
                queue.add(node);
            }
            
            //下面先通過(guò)isLeftChild判斷index,
            //再修改isLeftChild的符號(hào)的順序,十分巧妙
            if (!isLeftChild) {
                index++;
            }
            isLeftChild = !isLeftChild;
        }
        return root;
    }
}
更輕便的解法
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "null";
        StringBuilder sb = new StringBuilder();
        sb.append(root.val);
        String left = serialize(root.left);
        String right = serialize(root.right);
        sb.append(","+left+","+right);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] strs = data.split(",");
        Queue q = new LinkedList<>();
        for (String str: strs) {
            q.offer(str);
        }
        return helper(q);
    }
    
    public TreeNode helper(Queue q) {
        String str = q.poll();
        if (str.equals("null")) return null;
        TreeNode root = new TreeNode(Integer.parseInt(str));
        root.left = helper(q);
        root.right = helper(q);
        return root;
    }
}

For this problem, we are required to implement two methods: serialization and deserialization.

For the serialization part, we are given a TreeNode root. First of all, I am gonna check whether the root is null because I will use a recursion for this method. And I will create a StringBuilder, sb, to store the value of each node.
I will first append root.val to the StringBuilder. Then I will do the recursion twice, for root.left and root.right, to get left child part and right child part done. Next, I will arrange them with comma.

For the deserialization part, we are given a String of data (values of nodes). First, I will use data.split(",") method to separate data into String array. To use DFS, we will restructure this String array by using Queue, as Queue has FIFO property. So we put the String array into the Queue q, and call its DFS function for q.
In DFS function, we know that nodes in q are distributed into left part and right part. This would make the recursion simple by directly calling recursion for root.left and root.right as q is ordered.

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65458.html

相關(guān)文章

  • [LintCode/LeetCode] Balanced Binary Tree

    摘要:根據(jù)二叉平衡樹(shù)的定義,我們先寫(xiě)一個(gè)求二叉樹(shù)最大深度的函數(shù)。在主函數(shù)中,利用比較左右子樹(shù)的差值來(lái)判斷當(dāng)前結(jié)點(diǎn)的平衡性,如果不滿(mǎn)足則返回。 Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as...

    morgan 評(píng)論0 收藏0
  • [LintCode/LeetCode] Binary Tree Pruning

    Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...

    rockswang 評(píng)論0 收藏0
  • [LintCode/LeetCode] Construct Binary Tree from Tr

    摘要:做了幾道二分法的題目練手,發(fā)現(xiàn)這道題已經(jīng)淡忘了,記錄一下。這道題目的要點(diǎn)在于找的區(qū)間。邊界條件需要注意若或數(shù)組為空,返回空當(dāng)前進(jìn)到超出末位,或超過(guò),返回空每次創(chuàng)建完根節(jié)點(diǎn)之后,要將加,才能進(jìn)行遞歸。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...

    馬忠志 評(píng)論0 收藏0
  • [LintCode/LeetCode] Binary Tree Maximum Path Sum

    摘要:調(diào)用函數(shù)更新路徑和的最大值,而函數(shù)本身需要遞歸,返回的是單邊路徑和。所以函數(shù)要返回的是,主函數(shù)中返回的卻是最上一層根節(jié)點(diǎn)處和的較大值,與之前遍歷過(guò)所有路徑的最大值之間的最大值。 Problem Given a binary tree, find the maximum path sum. The path may start and end at any node in the tre...

    cnTomato 評(píng)論0 收藏0
  • [LintCode/LeetCode] Binary Tree Zigzag Level Orde

    Problem Given a binary tree, return the zigzag level order traversal of its nodes values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tr...

    AlphaGooo 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<