天天看點

331. 驗證二叉樹的前序序列化# # # #

序列化二叉樹的一種方法是使用前序周遊。當我們遇到一個非空節點時,我們可以記錄下這個節點的值。如果它是一個空節點,我們可以使用一個标記值記錄,例如 #。

_9_
/   \
           

3 2

/ \ /

4 1 # 6

/ \ / \ / \

# # # #

例如,上面的二叉樹可以被序列化為字元串 “9,3,4,#,#,1,#,#,2,#,6,#,#”,其中 # 代表一個空節點。

給定一串以逗号分隔的序列,驗證它是否是正确的二叉樹的前序序列化。編寫一個在不重構樹的條件下的可行算法。

每個以逗号分隔的字元或為一個整數或為一個表示 null 指針的 ‘#’ 。

你可以認為輸入格式總是有效的,例如它永遠不會包含兩個連續的逗号,比如 “1,3” 。

示例 1:

輸入: “9,3,4,#,#,1,#,#,2,#,6,#,#”

輸出: true

示例 2:

輸入: “1,#”

輸出: false

示例 3:

輸入: “9,#,#,1”

輸出: false

法一:建樹

class Solution {
public:
   bool dfs(vector<string> &nodes,int &pos){
        if(pos>=nodes.size()) return false;
        if(nodes[pos]=="#"){
            pos++;
            return true;
        } 
        pos++;
        if(!dfs(nodes,pos)) return false;
        if(!dfs(nodes,pos)) return false;
        return true;
    }
    bool isValidSerialization(string preorder) {
        stringstream ss(preorder);
        vector<string> nodes;
        string str = "";
        while(getline(ss, str, ',')){
            nodes.push_back(str);
        }
        int pos = 0;
        return  dfs(nodes,pos)&&pos>=nodes.size();
    }
};
           

法二:棧

class Solution {
public:
    bool isValidSerialization(string preorder) {
        stringstream ss(preorder);
        vector<string> nodes;
        int index = 0;
        string str = "";
        while(getline(ss, str, ',')){
            nodes.push_back(str);
            index++;
            while(index>=3&&nodes[index-1]=="#"&&nodes[index-2]=="#"){
              nodes.pop_back();
              nodes.pop_back();
              index = index-2;
              if(nodes[index-1]=="#") return false;
              nodes[index-1] = "#";
            } 
            
        }
        return nodes.size() == 1 && nodes[0] == "#";
    }
};
           

法三: 出入度

class Solution {
public:
    bool isValidSerialization(string preorder) {
        stringstream ss(preorder);
        int indegree = -1,outdegree = 0;
        string str = "";
        while(getline(ss, str, ',')){
            indegree++;
            if(outdegree<indegree) return false;
            if(str!="#") outdegree+=2;
        }
        return outdegree==indegree;
    }
};