1. 程式人生 > >[LeetCode] 331. Verify Preorder Serialization of a Binary Tree Java

[LeetCode] 331. Verify Preorder Serialization of a Binary Tree Java

sep find with har ted 分支 input enc equal

題目:

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node‘s value. If it is a null node, we record using a sentinel value such as #.

     _9_
    /      3     2
  / \   /  4   1  #  6
/ \ / \   / # # # #   # #

For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#"

, where # represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character ‘#‘ representing null

pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".

Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true

Example 2:
"1,#"
Return false

Example 3:
"9,#,#,1"
Return false

題意及分析:給出一個二叉樹的前序遍歷,要求判斷該二叉樹是否合法。

第一種方法:觀察可以得知,每一個葉節點的結構是“數字,#,#”,所以我們把所有的這樣的格式都替換成一個“#”,不斷地收縮,直到縮到最後應該是一個#。代碼如下:

public class Solution {
    public boolean isValidSerialization(String preorder) {
        String[] strings=preorder.split(",");
        boolean res=false;
        List<String> list=new ArrayList<>();
        //每一個葉節點的結構是“數字,#,#”,所以我們把所有的這樣的格式都替換成一個“#”,不斷地收縮,直到縮到最後應該是一個#
        for(int i=0;i<strings.length;i++){
            String str = strings[i];
            list.add(str);
            //收縮
            while(list.size()>=3&&list.get(list.size()-1).equals("#")&&list.get(list.size()-2).equals("#")&&!list.get(list.size()-3).equals("#")){
                list.remove(list.size()-1);
                list.remove(list.size()-1);
                list.remove(list.size()-1);
                list.add("#");
            }
        }
        
        if(list.size()==1&&list.get(0).equals("#"))
            res = true;
        // System.out.println(res);
        return res;
    }
}

第二種方法:

在構建的過程中,記錄出度與入度之差,記為diff = outdegree - indegree

當遍歷節點時,我們令diff - 1(因為節點提供了一個入度)。如果diff<0,返回false;如果節點非空,再令diff + 2(因為節點提供了2個出度)。

最後判斷diff==0;

理解:如果在遍歷過程中的某時刻,系統的入度>出度,則說明當前序列中出現過的所有分支節點的“空閑分支”均已用完,後序節點沒有辦法掛載到之前出現的節點之上,從而判定先序遍歷的序列是不合法的。

代碼如下:

public boolean isValidSerialization(String preorder) {
        String[] res = preorder.split(",");
        int diff = 1;
        for (String each : res) {
            if (--diff < 0) {
                return false;
            }
            if (!"#".equals(each)) {
                diff += 2;
            }
        }
        return diff == 0;
    }

  

[LeetCode] 331. Verify Preorder Serialization of a Binary Tree Java