題目:
用特殊的方法先序遍歷而成的字符串,判斷它可不可以恢復成一個二叉樹。
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;
}
}
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;
}