Leetcode -- Verify Preorder Serialization of a Binary Tree

本文介绍两种算法来验证一个字符串是否为正确的二叉树先序遍历序列化形式,无需重建树。一种使用栈结构删除叶子节点,另一种通过计算节点出入度差值判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值