LeetCode 331. Verify the pre-order serialization of the binary tree

1. Title

One way to serialize a binary tree is to use preorder traversal.
When we encounter a non-empty node, we can record the value of this node.
If it is an empty node, we can use a tag value record, such as #.

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

For example, the above binary tree can be serialized as a string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents an empty node.

Given a sequence of comma-separated sequences, verify that it is the correct preorder serialization of the binary tree.
Write a feasible algorithm without reconstructing the tree .

Each character separated by a comma is either an integer or a '#' representing a null pointer.

你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。
示例 1:
输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
输出: true

示例 2:
输入: "1,#"
输出: false

示例 3:
输入: "9,#,#,1"
输出: false

Source: LeetCode
Link: https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

2. Problem solving

Similar topics: LeetCode 297. Serialization and deserialization of binary trees (preorder traversal & sequence traversal)

  • There is always one more empty node than the effective node
  • Initial degree is 1, encounter number +1, encounter # -1
  • In the process, degree must not be equal to zero, equal to zero is equivalent to the end
  • Must be equal to 0 at the end
class Solution {
public:
    bool isValidSerialization(string preorder) {
    	if(preorder[0]=='#')
    		return preorder.size()==1;//根节点为空
    	int degree = 1, i, n = preorder.size();
    	for(i = 0; i < n-1; ++i)
    	{
    		if(i==0 || (preorder[i]==','&& isdigit(preorder[i+1])))
    			degree++;//数字
    		else if(preorder[i] == ',' && preorder[i+1]=='#')
    			degree--;//空节点
    		if(degree==0 && i != n-2)
    			return false;//过程中等于0,不行
    	}
    	return degree==0;
    }
};

4 ms 6.8 MB

Published 905 original articles · Like 2844 · Visit 490,000+

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105679759