331.验证二叉树的前序序列化

前序遍历结果判断二叉树是否完整的非二叉树方法

题目:

在这里插入图片描述

题目分析:

首先,前序遍历的特点是,(以题目示例为例)假设我们从根节点9出发,前序遍历的第一个节点是3,这时候,所有的操作都是基于3来执行的,除非3被更深的节点(4或1)覆盖(就如同3覆盖根节点9一般)或者3前序遍历结束,回到了根节点9.

这么一分析,这似乎就是栈结构嘛!

假设我们将每个节点都设置一个计数器,遇到一个非‘#’节点就将其压入栈,如果每遇到一个他的子节点,就加一,如果已经为2就将节点弹出栈(说明这个节点下面的都已经被遍历过了),如果遇到"#",只加一,不压栈。

代码:
class Solution {
public:
    // Trees always have two branches, or null; And branches also have two branches, or null.
    // So we create a struct that has to count whether current branches have had two branches or null
    struct node{
        int count;
        //char myChar;
        node(){
            count = 0;
        }
    };

    bool isValidSerialization(string preorder) {

        stack<node> tree;
        int length = preorder.length();
        int index = 0;
        bool hasStart = false;

        if(length == 0) return false;

        if(length == 1 && preorder[0] == '#') return true;

        while(index < length){
            // when we meet ',', ignore it
            if(preorder[index] == ',')index++;

            // when we first time to use stack, init it
            if(!hasStart && preorder[index] != '#'){
                tree.push(node());
                index ++;
                hasStart = true;
            }else {

                // if stack is empty, break
                if (tree.empty())break;

                // if node need to be popped
                if (tree.top().count == 2) {
                    tree.pop();
                } else {
                    // if we meet '#', count times without pushing it
                    if (preorder[index] == '#') {
                        tree.top().count++;
                        index++;
                    } else {
                        while(preorder[index] <= '9' && preorder[index] >= '0')index++;
                        
                        tree.top().count++;
                        tree.push(node());
                        index++;
                    }
                }
            }

        }

        // popping all the node that it's count is 2
        while(!tree.empty() && tree.top().count == 2) tree.pop();

        // incomplete -> false
        if(index < length ) return false;
        else if(!tree.empty()) return false;
        // complete -> true
        else return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值