LeetCode.331 Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:java手机游戏安卓版 编辑:程序博客网 时间:2024/06/06 03:52

题目:

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.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".

Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true

Example 2:
"1,#"
Return false

Example 3:
"9,#,#,1"
Return false

分析:

class Solution {    public boolean isValidSerialization(String preorder) {        //给定二叉树前序的字符串,判断其是否满足二叉树条件序列化条件。当节点为空时,用#替代        //思路:由于给定的序列串是满足前序条件的,根据二叉树的节点的性质。每当添加一个节点入度+1.当节点不为叶子节点,出度-2        //当出度和入度相等,说明是满足情况的序列串                String [] strs=preorder.split(",");        //初始化根节点,入度为-1        int degree=-1;        for(int i=0;i<strs.length;i++){            //入度+1            degree++;            if(degree>0) return false;            //若不是叶子节点,则出度-2            if(!strs[i].equals("#")) degree-=2;        }                return degree==0;    }}


阅读全文
0 0