Advertisement
hoangreal

Verify preorder traversal binary tree

Oct 20th, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | Source Code | 0 0
  1. // Given a string of comma-separated values preorder,
  2. // return true if it is a correct preorder traversal serialization of a binary tree.
  3.  
  4. /* Explanation
  5.  
  6. In a binary tree, if we consider null as leaves, then
  7.  
  8. All non-null node provides 2 outdegree and 1 indegree (2 children and 1 parent), except root
  9. All null node provides 0 outdegree and 1 indegree (0 child and 1 parent).
  10.  
  11. Suppose we try to build this tree. During building, we record diff = outdegree - indegree.
  12. When the next node comes, we then decrease diff by 1, because the node provides an in degree.
  13. If the node is not null, we increase diff by 2, because it provides two out degrees.
  14.  
  15. If a serialization is correct, diff should never be negative and diff will be zero when finished.
  16. */
  17. public boolean isValidSerialization(String preorder) {
  18.     String[] nodes = preorder.split(",");
  19.     int diff = 1;
  20.     for (String node: nodes) {
  21.         if (--diff < 0) return false;
  22.         if (!node.equals("#")) diff += 2;
  23.     }
  24.     return diff == 0;
  25. }
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement