JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

Code

class Solution {
    public boolean isValidSerialization(String preorder) {
        // 每个非叶子节点都有2出度和1入度, 除了根节点
        // 每个叶子节点都有0出度和1入度
        String[] nodes = preorder.split(",");
        // 让根节点有一个入度
        // degree = outDegree - inDegree
        int degree = 1;
        for(String node : nodes){
            // 新来一个节点,要消耗一个度
            // 如果此时没有度可以用,那么就返回false
            if(--degree < 0){
                return false;
            }
            // 如果不是叶子节点,那就要增加两个出度
            if(!node.equals("#")){
                degree += 2;
            }
        }
        return degree == 0;
    }
}
class Solution {
    public boolean isValidSerialization(String preorder) {
        Stack<String> stack = new Stack<>();

        for (String s : preorder.split(",")){
            while (!stack.isEmpty() && stack.peek().equals("#") && s.equals("#")) {
                stack.pop();
                if(stack.isEmpty()){
                    return false;
                }
                stack.pop();
            }
            stack.push(s);
        }

        return stack.size() == 1 && stack.peek().equals("#");
    }
}