前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Tree - 331. Verify Preorder Serialization of a Binary Tree

Tree - 331. Verify Preorder Serialization of a Binary Tree

作者头像
ppxai
发布2020-09-23 17:34:04
2720
发布2020-09-23 17:34:04
举报
文章被收录于专栏:皮皮星球皮皮星球

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

代码语言:javascript
复制
     _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".

思路:

读取到的结构只要符合二叉树性质而且不会在未读完之前就满足leaves = nodes + 1(完整的二叉树)即可

代码:

go:

代码语言:javascript
复制
func isValidSerialization(preorder string) bool {

    leaves := 0
    node := 0
    pres := strings.Split(preorder,",")
	for i, s := range pres {
		if s == "#" {
			leaves++
		} else {
			node++
		}
		if leaves > node + 1{
			return false
		}
		if leaves == node + 1 && i < len(pres)- 1 {
			return false
		}
    }
    
	if leaves != node + 1{
		return false
    }
    return true
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年08月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档