LeetCode 331 Verify Preorder Serialization of a Binary Tree (栈 模拟)

244 篇文章 0 订阅
37 篇文章 0 订阅

One way to serialize a binary tree is to use preorder 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 values preorder, return true if it is a correct preorder traversal serialization of a binary tree.

It is guaranteed that 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
  • preorder consist of integers in the range [0, 100] and '#' separated by commas ','.

题目链接:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/

题目大意:给一个二叉树先序遍历序列化后的字符串,在不能构造二叉树的情况下判断此序列化结果是否正确

题目分析:先序遍历是中左右的顺序,可按照顺序将序列化的值压栈(空为-1),出栈的规则为必须在栈顶找到两个连续的-1,当某个值出栈后,需要将该值变为-1,相当于其父节点的孩子节点此时为空,如果最终栈中只剩一个-1,则为合法状态

3ms,时间击败91%

class Solution {
    public boolean isValidSerialization(String preorder) {
        char[] s = preorder.toCharArray();
        int n = s.length, top = 0;
        int[] stk = new int[n + 1];
        if (n > 0 && s[n - 1] != '#') {
            return false;
        }

        int num = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == ',') {
                if(s[i - 1] != '#') {
                    stk[++top] = num;
                }
                num = 0;
            } else if (s[i] == '#') {
                stk[++top] = -1;
            } else {
                num = num * 10 + (s[i] - '0');
            }
        }
        while (top > 1) {
            if (top > 1 && stk[top] == -1 && stk[top - 1] == -1) {
                top -= 2;
            } else {
                break;
            }
            int tmp = top;
            while (tmp > 1 && stk[tmp] == -1) {
                tmp--;
            }
            if (stk[tmp] == -1) {
                return false;
            }
            stk[tmp] = -1;
        }
        return top == 1 && stk[top] == -1;
    }
}

更简单的做法是直接根据出入度判断,遇到数字度数+2(左右孩子),遍历到每个位置度数-1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值