[LeetCode]Verify Preorder Serialization of a Binary Tree
来源:互联网 发布:软件质量保证计划事例 编辑:程序博客网 时间:2024/05/16 12:16
如果在还未完全遍历整个树的时候就已经nonleaves + 1 == leaves,然而剩余未遍历的部分仍然是由若干个full tree组成的,这样整个树就不能满足nonleaves + 1 == leaves的条件。public class Solution { public boolean isValidSerialization(String preorder) { if(preorder == null || preorder.length() == 0) return false; String[] cache = preorder.split(","); int leaves = 0, nonleaves = 0, i = 0; for (i = 0; i < cache.length && nonleaves + 1 != leaves; i++) { if(cache[i].equals("#")) leaves++; else nonleaves++; } // The given tree is a full tree, if and only if nonleaves + 1 == leaves && i == cache.length. // Because preorder count root node first. return nonleaves + 1 == leaves && i == cache.length; }}
如果在还未完全遍历整个树的时候就已经nonleaves + 1 == leaves,然而剩余未遍历的部分仍然是由若干个full tree组成的,这样整个树就不能满足nonleaves + 1 == leaves的条件。
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
判断一个序列是不是二叉树的前序遍历,不能重构树
解法二:
每遇到两个null就把这两个与前一个非null结合,变为null压回栈中
public class Solution { public boolean isValidSerialization(String preorder) { Stack<String> stack = new Stack(); String[] arr = preorder.split(","); stack.push(arr[0]); for (int i = 1; i < arr.length; i++) { if (arr[i].equals("#")) { while (stack.size() >= 2 && stack.peek().equals("#")) { String s1 = stack.pop(); String s2 = stack.pop(); if (!(s1.equals("#") && !s2.equals("#"))) { return false; } } } stack.push(arr[i]); } return stack.size() == 1 && stack.peek().equals("#"); }}
0 0
- leetcode Verify Preorder Serialization of a Binary Tree
- Leetcode: Verify Preorder Serialization of a Binary Tree
- LeetCode Verify Preorder Serialization of a Binary Tree
- leetcode 331. Verify Preorder Serialization of a Binary Tree
- [LeetCode]331. Verify Preorder Serialization of a Binary Tree
- [leetcode] Verify Preorder Serialization of a Binary Tree
- [Leetcode]Verify Preorder Serialization of a Binary Tree
- 【LeetCode】331. Verify Preorder Serialization of a Binary Tree
- LeetCode 331. Verify Preorder Serialization of a Binary Tree
- LeetCode Verify Preorder Serialization of a Binary Tree
- [leetcode-331]Verify Preorder Serialization of a Binary Tree
- LeetCode *** 331. Verify Preorder Serialization of a Binary Tree
- [LeetCode]Verify Preorder Serialization of a Binary Tree
- LeetCode 331. Verify Preorder Serialization of a Binary Tree
- leetcode verify Preorder Serialization of a Binary Tree
- 【Leetcode】Verify Preorder Serialization of a Binary Tree
- LeetCode No331. Verify Preorder Serialization of a Binary Tree
- LeetCode:Verify Preorder Serialization of a Binary Tree
- 几个常用的Linux监控脚本
- 集成tiles3时遇到的问题,mark一下
- 静态注册广播接收者
- 网易游戏笔试题:输入一个数n,返回一个数组,数组中每个元素对应[0,n]每个数的二进制中1的个数
- iOS地图开发-高德地图
- [LeetCode]Verify Preorder Serialization of a Binary Tree
- Java常用之String.valueOf、toString、(String)
- Android支持库概述
- Spring3 升级Spring 4
- 大屏拼接控制器的发展历程与现状分析
- 技术文章写作及运营的技巧:分析篇 | 什么样的文章受欢迎?
- [Data Structure] Maximum Subsequence Sum
- HDU 1050(其实应该是线段树但规模太小,没必要)
- php序列化存储数据