Middle-题目51:331. Verify Preorder Serialization of a Binary Tree

本文介绍了一种方法来验证给定的字符串是否为有效二叉树的前序遍历序列,提供了两种算法实现,一种使用堆栈,另一种通过计数进行判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Middle-题目51:331. 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.
题目大意:
给出一个用逗号分隔的字符串,其中数字代表节点的值,#号代表空节点,判断是否是一个合法的二叉树的前序遍历序列。
题目分析:
方法一(朴素解法):用堆栈,每次遇到一个数字或者#号都入栈,如果栈顶的前三个元素依次是#,#,数字,则把它们三个都弹出来,再把#号压入栈(代表去掉了一个叶子节点),如此往复若最后栈里只有一个#(所有节点遍历完毕),则是合法的。
方法二:从discuss中看到的一个神算法,好像机理是一样的,只是没有用到堆栈,大致意思是,初始化一个变量count从后向前搜索,遇到#号就+1,遇到数字就-1,看最后是不是1,如果中途不够减则返回false。此算法具体思路及验证正确性,还有待进一步研究。
源码:(language:java)
方法一:

public class Solution {
    public boolean isValidSerialization(String preorder) {
        String[] nodes = preorder.split(",");
        Stack<String> stack = new Stack<String>();
        for(String str : nodes) {
            stack.push(str);
            int size = stack.size();
            while(size > 2 && stack.get(size-1).equals("#") && stack.get(size-2).equals("#") && !stack.get(size-3).equals("#")) {
                stack.pop();
                stack.pop();
                stack.pop();
                stack.push("#");
                size = stack.size();
            }   
        }
        return stack.size() == 1 && stack.peek().equals("#");
    }
}

方法二:

public class Solution {
    public boolean isValidSerialization(String preorder) {
        int len = preorder.length();
        int count = 0;
        for(int i=len-1; i>=0; i--){
            char tmp = preorder.charAt(i);
            if(tmp == ','){
                continue;
            }else if(tmp == '#'){
                count++;
            }else if(tmp != ',' && tmp != '#' && i!=0 && preorder.charAt(i-1)!=','){
                continue;
            }else{
                if(count<2){
                    return false;
                }else{
                    count--;
                }
            }
        }
        return count==1;
    }
}

成绩:
方法一:25ms,beats 10.82%,众数11ms,22.68%
方法二:4ms,beats 98.75%
Cmershen的碎碎念:
其实方法一浪费时间主要是在基于正则表达式的split函数和STL中堆栈函数,而方法二直接对数组操作,但似乎本质是一样的(因为方法二中的count也是统计的#号个数)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值