Leetcode -- Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:linux中expect 编辑:程序博客网 时间:2024/05/24 02:14

题目描述

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

解答:

解法一:
关键思想是利用先序遍历的特征。首先是根节点然后左子树右子树,“#”代指空节点,依据这种遍历的特征,我们可以不断删除叶子节点。
利用栈结构,不断删除叶子节点,例如遇到“4 # #”的时候删除并换成“#”,直到最后不能再删除。例如图示。


public static boolean isValidSerialization(String preorder) {List<String> stack = new ArrayList<String>();String[] arr = preorder.split(",");for (int i = 0; i < arr.length; i++) {stack.add(arr[i]);while (stack.size() >= 3 && stack.get(stack.size() - 1).equals("#")        && stack.get(stack.size() - 2).equals("#")        && !stack.get(stack.size() - 3).equals("#")) {stack.remove(stack.size() - 1);stack.remove(stack.size() - 1);stack.remove(stack.size() - 1);stack.add("#");}}if (stack.size() == 1 && stack.get(0).equals("#")) return true;else return false;}
解法二:
把二叉树的空节点当作叶子节点#表示。所有的叶子节点提供1个入度0个出度,非叶子节点2个出度1个入度(根除外),又二叉树的性质叶子节点个数=非叶子个数+1. 所以我们可以一个一个的遍历,计算diff = outdegree –indegree。对于内部节点,入度减一出度加二,叶子节点入度减一,如是正确序列结果diff必为0.
public static boolean isValidSerialization(String preorder) {String[] nodes = preorder.split(",");int diff = 1;for (String node : nodes) {// 入度减一if (--diff < 0) return false;// 出度加二if (!node.equals("#")) diff += 2;}return diff == 0;}

refer:
https://discuss.leetcode.com/topic/35976/7-lines-easy-java-solution


0 0
原创粉丝点击