331. Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:数控冲床编程教学 编辑:程序博客网 时间:2024/06/06 08:56

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

给出一个前序序列,检查这样的前序序列是否合法。

每到一个节点,如果节点的左子树或者右子树空,要有相应的‘#’表示。

利用前面类似于非递归,迭代中序遍历的过程,建立一个栈,每次遇到相应的空树就出栈一个节点,并把扫描指针往后移动,如果前序序列是合法的,就不会出现中途栈空的情况,指针最后指向的必然是null,如果不是null,说明最后的节点的左右子树虽然空了但是没有用相应的字符表示。

 public static boolean isValidSerialization(String preorder){String[] strs=preorder.split(",");int len=strs.length;if(len<2&&strs[0].compareTo("#")==0)return true;Stack<Character> stack=new Stack<>();int i=0;while(i<len){char c=strs[i].charAt(0);if(c=='#'){if(stack.isEmpty()){if(i<len-1)return false;else {break;}}stack.pop();if(i+1==len)return false;}else {stack.push(c);}i++;}return stack.isEmpty();}




update 2016.07.30


栈只是计数功能,可以用一个变量代替,指示栈中元素个数


可以预先往栈里压入一个冗余的元素,这样在最后只要检查是否栈空就可以了,不过仍然要警惕中途栈空的情况,中途栈空是不合法的,例如

“#,7,6,9,#,#,#”,如果预先压入冗余元素又不检查中途栈空就会WA




public static boolean isValidSerialization(String preorder){String[] strs=preorder.split(",");int len=strs.length;if(len<2&&strs[0].compareTo("#")==0)return true;int i=0;int top=1;while(i<len){char c=strs[i].charAt(0);if(c=='#'){if(top==0||(top==1&&i<len-1))return false;top--;}else {top++;}i++;}return top==0;}



0 0
原创粉丝点击