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.

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

题目含义:判断给定是字符串是不是一个正确的按照先序顺序遍历的二叉树的字符串,空节点用#表示

思路一:如果遇上连续两个#,连同前面的数字,三个一组被替换为#后再次加入stack。否则直接加入stack,最后stack中只应该剩下一个#才对

 

 1     public boolean isValidSerialization(String preorder) {
 2         if (preorder == null) return false;
 3         // using a stack, scan left to right
 4         // case 1: we see a number, just push it to the stack
 5         // case 2: we see #, check if the top of stack is also #
 6         // if so, pop #, pop the number in a while loop, until top of stack is not #
 7         // if not, push it to stack
 8         // in the end, check if stack size is 1, and stack top is #
 9         Stack<String> st = new Stack<>();
10         String [] strs = preorder.split(",");
11         for (int i=0;i<strs.length;i++)
12         {
13             String cur = strs[i];
14             while (cur.equals("#") && !st.isEmpty() && st.peek().equals(cur))
15             {
16                 st.pop();
17                 if (st.isEmpty()) return false;
18                 st.pop();
19             }
20             st.push(cur);
21         }
22         return st.size()==1&&st.peek().equals("#");
23     }

方法二:遇上数字节点入口减1,出口加2(根节点只有出口加2),遇上#节点只有入口减一,最后整个结果应该为0

 1     public boolean isValidSerialization(String preorder) {
 2         if (preorder == null) return false;
 3 //        入-  减一
 4 //        出  加二
 5 //        最后的总和应该是0
 6         String[] nodes = preorder.split(",");
 7         int degree = 1;
 8         for (int i = 0; i < nodes.length; i++) {
 9             degree -= 1;
10             if (degree < 0) return false;
11             if (!nodes[i].equals("#")) degree += 2;
12         }
13         return degree == 0;        
14     }

 

posted @ 2017-10-24 21:53  daniel456  阅读(171)  评论(0编辑  收藏  举报