1. 程式人生 > 其它 >【leetcode】331. Verify Preorder Serialization of a Binary Tree

【leetcode】331. Verify Preorder Serialization of a Binary Tree

  One way to serialize a binary tree is to usepreorder 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'#'.

  

  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 valuespreorder, returntrueif it is a correct preorder traversal serialization of a binary tree.It isguaranteedthat 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".
  Note:You are not allowed to reconstruct the tree.   Example 1:   Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true   Example 2:   Input: preorder = "1,#" Output: false   Example 3:   Input: preorder = "9,#,#,1" Output: false   Constraints:
  • 1 <= preorder.length <= 104
  • preoderconsist of integers in the range[0, 100]and'#'separated by commas','.
  此題是參考的是grandyang大佬的解題思路:
     這道題給了我們一個類似序列化二叉樹後的字串,關於二叉樹的序列化和去序列化可以參見我之前的部落格Serialize and Deserialize Binary Tree,這道題讓我們判斷給定是字串是不是一個正確的序列化的二叉樹的字串。那麼根據之前那邊部落格的解法,我們還是要用istringsteam來操作字串,C++裡面沒有像Java那樣有字串的split函式,可以直接分隔任意字串,我們只能使用getline這個函式,來將字串流的內容都存到一個vector陣列中。我們通過舉一些正確的例子,比如"9,3,4,#,#,1,#,#,2,#,6,#,#" 或者"9,3,4,#,#,1,#,#,2,#,6,#,#"等等,可以觀察出如下兩個規律:   1. 數字的個數總是比#號少一個   2. 最後一個一定是#號   那麼我們加入先不考慮最後一個#號,那麼此時數字和#號的個數應該相同,如果我們初始化一個為0的計數器,遇到數字,計數器加1,遇到#號,計數器減1,那麼到最後計數器應該還是0。下面我們再來看兩個返回False的例子,"#,7,6,9,#,#,#"和"7,2,#,2,#,#,#,6,#",那麼通過這兩個反例我們可以看出,如果根節點為空的話,後面不能再有節點,而且不能有三個連續的#號出現。所以我們再加減計數器的時候,如果遇到#號,且此時計數器已經為0了,再減就成負數了,就直接返回False了,因為正確的序列裡,任何一個位置i,在[0, i]範圍內的#號數都不大於數字的個數的。當迴圈完成後,我們檢測計數器是否為0的同時還要看看最後一個字元是不是#號。參見程式碼如下:   
class
Solution { public: bool isValidSerialization(string preorder) { //沒有python 以及java的split的分割函式 這種方式用輸入流來解決 //這題是完全沒思路 istringstream in(preorder); vector<string> v; string t=""; int cnt=0; while (getline(in,t,',')) v.push_back(t); for(int i=0;i<v.size()-1;i++) { if(v[i]=="#") { if(cnt==0) return false; cnt--; } else cnt++; } return cnt==0 && v.back()=="#"; } };