zoukankan      html  css  js  c++  java
  • 331 Verify Preorder Serialization of a Binary Tree 验证二叉树的前序序列化

    序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录这个节点的值。如果它是一个空节点,我们可以使用一个标记值,例如 #。
         _9_
        /  
       3     2
      /    /
     4   1  #  6
    / /    /
    # # # #   # #
    例如,上面的二叉树可以被序列化为字符串"9,3,4,#,#,1,#,#,2,#,6,#,#",其中#代表一个空节点。
    给定一串以逗号分隔的值,验证它是否是正确的二叉树的前序序列化。想出一种在不重构树的情况下的可行算法。
    每个逗号分隔的字符串中的值肯定是一个整数或者一个表示null指针的'#'。
    你可以假定输入格式总是有效的,例如它永远不能包含两个连续的逗号,比如"1,,3"。
    示例 1:
    "9,3,4,#,#,1,#,#,2,#,6,#,#"
    返回 true
    示例 2:
    "1,#"
    返回 false
    示例 3:
    "9,#,#,1"
    返回 false

    详见:https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/

    C++:

    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            istringstream in(preorder);
            vector<string> v;
            string t = "";
            int cnt = 0;
            while (getline(in, t, ','))
            {
                v.push_back(t);
            }
            for (int i = 0; i < v.size() - 1; ++i)
            {
                if (v[i] == "#")
                {
                    if (cnt == 0)
                    {
                        return false;
                    }
                    --cnt;
                } 
                else
                {
                    ++cnt;
                }
            }
            return cnt == 0 && v.back() == "#";
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/5174738.html

  • 相关阅读:
    Discuz!NT 系统架构分析
    jquery pager
    Nhibernate分页方法
    Discuz nt模板机制
    WTclient创建OPC client方法
    OPC
    Regular Expressions in Java
    How to use VS to manipulate Access
    OPC客户端设计
    How to use VS to manipulate Excel使用MFC读写Excel
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8833306.html
Copyright © 2011-2022 走看看