331. Verify Preorder Serialization of a Binary Tree

題目:

用特殊的方法先序遍歷而成的字符串,判斷它可不可以恢復成一個二叉樹。

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;
}



發佈了51 篇原創文章 · 獲贊 23 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章