博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Verify Preorder Serialization of a Binary Tree
阅读量:4546 次
发布时间:2019-06-08

本文共 2227 字,大约阅读时间需要 7 分钟。

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

 

题目:判断二叉树的先序序列正确性(不重建树)

思路:二叉树先序遍历序列类似于进栈出栈的过程,可以理解为每个新节点的产生都新增需要一个 '#' 在序列中。根节点需要两个 '#' ,因此节点总数应该比 '#' 总数少一个。

做法:借助一个栈,遇数进栈,遇 '#' 出栈,遍历到序列最后应该是多出一个 '#' 。另外特殊考虑空树的情况即可。

 

1 class Solution { 2 public: 3     bool isValidSerialization(string preorder) { 4         stack
stack1; 5 string tmpstr = ""; 6 int i = 0; 7 int length = preorder.size(); 8 bool getnumber = 0; 9 if(length == 1 && preorder[0] == '#'){10 return true;11 }12 while(i < length - 1){13 if(preorder[i] == '#'){14 if(stack1.empty()){15 return false;16 }else{17 stack1.pop();18 i ++;19 }20 }else if(preorder[i] == ','){21 if(getnumber){22 getnumber = false;23 stack1.push(tmpstr);24 tmpstr = "";25 i++;26 }else{27 i++;28 }29 }else{30 getnumber = true;31 tmpstr += string(1, preorder[i]);32 i++;33 }34 }35 if(stack1.empty() && preorder[i] == '#'){36 return true;37 }38 else{39 return false;40 }41 }42 };

 

转载于:https://www.cnblogs.com/suwish/p/5224645.html

你可能感兴趣的文章
Python_Openpyxl 简单说明
查看>>
three.js
查看>>
onInterceptTouchEvent和onTouchEvent
查看>>
Team Queue POJ - 2259 (队列)
查看>>
智能小车34:汇编与C语言一起玩
查看>>
WebView的背景设置成透明
查看>>
[PWA] 5. Hijacking one type of request
查看>>
【RabbitMQ】使用学习
查看>>
BZOJ3884: 上帝与集合的正确用法(欧拉函数 扩展欧拉定理)
查看>>
UVa 11889 (GCD) Benefit
查看>>
JavaScript 基础,登录前端验证
查看>>
自制反汇编逆向分析工具 总结 (一)
查看>>
Ubuntu 常用命令大全
查看>>
js数组方法forEach,map,filter,every,some实现
查看>>
Python3.7 + jupyter安装(CentOS6.5)
查看>>
纯CSS实现tooltip提示框,CSS箭头及形状之续篇--给整个tooltip提示框加个边框
查看>>
Spring @Scheduled 在tomcat容器里面执行两次
查看>>
浅谈MVC、MVP、MVVM架构模式的区别和联系
查看>>
3126Prime Path
查看>>
hdu3117(斐波那契数列,矩阵连乘)
查看>>