题目:
用特殊的方法先序遍历而成的字符串,判断它可不可以恢复成一个二叉树。
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.
思路:- 第一种思路(我的):一个可以恢复成二叉树的字串-根节点+左子树的字串+右子树的字串,用递归的方法来判断
- 第二种思路(男朋友的):通过二叉树的性质,所有二叉树中Null指针的个数=节点个数+1。因为一棵树要增加一个节点,必然是在null指针的地方增加一个叶子结点,也就是毁掉一个null指针的同时带来两个null指针,意味着每增加一个节点,增加一个null指针。然而最开始一颗空树本来就有一个null指针,因此二叉树中null指针的个数等于节点数+1。从头开始扫描这个字串,如果途中#的个数超了,或者字符串扫描完不满足等式则返回false。
程序:
class pointer {
int val = 0;
}
public class Solution {
public boolean helper(String[] pre, pointer p) {
if(p.val > pre.length - 1) return false;
if(pre[p.val].equals("#")) {p.val++; return true;}
else {
p.val++;
return helper(pre, p) && helper(pre, p);
}
}
public boolean isValidSerialization(String preorder) {
if(preorder == null ) return false;
String[] pre = preorder.split(",");
pointer p = new pointer();
return helper(pre, p) && p.val == pre.length;
}
}
下面是一个感觉很简洁的程序,来自leetcode discussion
https://leetcode.com/discuss/83824/7-lines-easy-java-solution
public 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;
}