简单粗暴,代码有待优化,不过自己独立完成,没有参考任何材料,还是比较满意的
package y2019.Algorithm.stack.medium;
import java.util.Stack;
/**
* @Auther: xiaof
* @Date: 2019/12/6 09:06
* @Description:331. 验证二叉树的前序序列化
*
* 序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,
* 我们可以使用一个标记值记录,例如 #。
*
* _9_
* / \
* 3 2
* / \ / \
* 4 1 # 6
* / \ / \ / \
* # # # # # #
* 例如,上面的二叉树可以被序列化为字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 代表一个空节点。
* 给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。
* 每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 '#' 。
* 你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。
*
* 示例 1:
* 输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
* 输出: true
* 示例 2:
* 输入: "1,#"
* 输出: false
* 示例 3:
* 输入: "9,#,#,1"
* 输出: false
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
public class IsValidSerialization {
/**
* 执行用时 : 10 ms , 在所有 java 提交中击败了 43.30% 的用户
* 内存消耗 : 35.5 MB , 在所有 java 提交中击败了 97.06% 的用户
* @param preorder
* @return
* by xiaof 2019年12月6日10:09:08
*/
public boolean solution(String preorder) {
if ("#".equals(preorder)) {
return true;
}
String[] eles = preorder.split(",");
boolean isRight = false;
//默认就是左节点,如果是右节点是#,那么就出栈,如果是左节点是#,那么就切换左右
Stack stack = new Stack(); //如果栈为空的时候,还有最后一个#,那么正好跳出循环
int index = 0;
String curEle = eles[0];
stack.push(eles[index]);
//开始遍历后续元素
for (index = 1; index < eles.length; ++index) {
if ("#".equals(curEle) && isRight) {
return false;
}
if ("#".equals(eles[index])) {
isRight = true;
if (stack.isEmpty()) {
//如果栈已经空了
break;
}
curEle = stack.pop();
} else {
stack.push(eles[index]);
isRight = false;
}
}
return stack.isEmpty() && index == (eles.length - 1);
}
public static void main(String[] args) {
String s = "9,3,4,#,#,1,#,#,2,#,6,#,#";
String s1 = "1,#";
String s2 = "1";
String s3 = "#";
String s4 = "#,#";
IsValidSerialization fuc = new IsValidSerialization();
fuc.solution(s4);
}
}
Original: https://www.cnblogs.com/cutter-point/p/11993633.html
Author: cutter_point
Title: 【LEETCODE】71、验证二叉树的前序序列化
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/570666/
转载文章受原作者版权保护。转载请注明原作者出处!