1 public class Solution { 2 public boolean isValidSerialization(String preorder) { 3 String[] nodes = preorder.split(","); 4 int tree = 0; 5 int leaves = 0; 6 for (int i = nodes.length - 1; i >= 0; i--) { 7 if (!nodes[i].equals("#")) { 8 tree++; 9 } else { 10 leaves++; 11 } 12 13 if (leaves - tree < 1) { 14 return false; 15 } 16 } 17 return leaves - tree == 1; 18 } 19 }
1. This is counting leaves and trees method. It should starting from end, which gareentee the leaves is larger than tree.
A nice regex work:
1 public class Solution { 2 public boolean isValidSerialization(String preorder) { 3 String s = preorder.replaceAll("\\d+,#,#", "#"); 4 return s.equals("#") || !s.equals(preorder) && isValidSerialization(s); 5 } 6 }