1. 程式人生 > 其它 >【LeetCode】331. Verify Preorder Serialization of a Binary Tree 驗證二叉樹的前序序列化(Medium)(JAVA)

【LeetCode】331. Verify Preorder Serialization of a Binary Tree 驗證二叉樹的前序序列化(Medium)(JAVA)

技術標籤:Leetcode二叉樹演算法javaleetcode資料結構

【LeetCode】331. Verify Preorder Serialization of a Binary Tree 驗證二叉樹的前序序列化(Medium)(JAVA)

題目地址: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/

題目描述:

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:

Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true

Example 2:

Input: "1,#"
Output: false

Example 3:

Input: "9,#,#,1"
Output: false

題目大意

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

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

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

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

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

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

解題方法

  1. 通過觀察可以知道,符合要求的樹結構,結尾肯定是 ‘#’
  2. 有多少個空節點,就有多少個樹節點 + 1個,也就是 空節點 == 樹節點 + 1,也就是 ‘#’ 個數 == 樹節點個數 + 1,除了最後一個 ‘#’ ,就是 ‘#’ 個數 = 樹節點個數
  3. 如何判斷樹節點?除了 ‘#’ 號後面的 ‘,’ ,每個樹節點後面都有一個 ‘,’
class Solution {
    public boolean isValidSerialization(String preorder) {
        if (preorder.length() == 0) return true;
        if (preorder.charAt(preorder.length() - 1) != '#') return false;
        int count = 0;
        for (int i = 0; i < preorder.length() - 1; i++) {
            if (preorder.charAt(i) == '#') {
                count--;
                i++;
            } else if (preorder.charAt(i) == ',') {
                count++;
            }
            if (count < 0) return false;
        }
        return count == 0;
    }
}

執行耗時:2 ms,擊敗了97.01% 的Java使用者
記憶體消耗:36.6 MB,擊敗了97.66% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新