LeetCode 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.

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

题意:

给定一个关于二叉树序列的字符串,其中每一个节点之间用","来分隔,在不建树的情况下,判断给定的这个序列是否是二叉树的先序遍历序列。其中如果碰到空节点用"#"来表示;并且不会出现"1,,3"这种分隔有多个逗号的情况。

题解:

考虑用堆栈来做,这个方法简单的说就是不断的砍掉叶子节点。最后看看能不能全部砍掉。

已例子一为例:”9,3,4,#,#,1,#,#,2,#,6,#,#” 遇到x # #的时候,就把它变为 #

我模拟一遍过程:

  1. 9,3,4,#,# => 9,3,# 继续读
  2. 9,3,#,1,#,# => 9,3,#,# => 9,# 继续读
  3. 9,#2,#,6,#,# => 9,#,2,#,# => 9,#,# => #
从以上步骤可以得到规律,也就是二叉树先序遍历的过程,此题按照倒退,可以发现如果出现的连续两个"#",那么可以和之前的那个非"#"的数字合并为一个"#",其实也就是考虑将一个节点的合并为它的父节点的左子树或者是右子树。
用堆栈来做,其中堆栈的头顶的元素可以用stack.get(stack.size() - 1)来得到,并且判断stack中的元素和某一个元素是否相等的方法不能用"==",而必须用equals来做。
代码如下:
public boolean isValidSerialization(String preorder)
	{
		Stack<String> stack = new Stack<String>();
		String[] num = preorder.split(",");
		for(int i = 0; i < num.length; i++)
		{
			stack.push(num[i]);
			while(stack.size() >= 3)
			{
				//这里必须要使用equals,如果用==就会报错
				if(stack.get(stack.size() - 1).equals("#") && stack.get(stack.size() - 2).equals("#") && !stack.get(stack.size() - 3).equals("#"))
				{
					stack.pop();
					stack.pop();
					stack.pop();
					stack.push("#");
				}
				else 
					break;
			}
		}
		//注意一种特殊的情况,如果是只有一个"#",那么返回的是true,而不是false。
		return stack.size() == 1 && stack.peek().equals("#");
	}
此外,还需要注意一种特殊情况,也就是只有一个"#"的情况,此表示没有节点,那么返回的是true,而不是false.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值