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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值