331. Verify Preorder Serialization of a Binary Tree
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 #
.
_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 public boolean isValidSerialization(String preorder) { 2 if (preorder == null) return false; 3 // using a stack, scan left to right 4 // case 1: we see a number, just push it to the stack 5 // case 2: we see #, check if the top of stack is also # 6 // if so, pop #, pop the number in a while loop, until top of stack is not # 7 // if not, push it to stack 8 // in the end, check if stack size is 1, and stack top is # 9 Stack<String> st = new Stack<>(); 10 String [] strs = preorder.split(","); 11 for (int i=0;i<strs.length;i++) 12 { 13 String cur = strs[i]; 14 while (cur.equals("#") && !st.isEmpty() && st.peek().equals(cur)) 15 { 16 st.pop(); 17 if (st.isEmpty()) return false; 18 st.pop(); 19 } 20 st.push(cur); 21 } 22 return st.size()==1&&st.peek().equals("#"); 23 }
方法二:
1 public boolean isValidSerialization(String preorder) { 2 if (preorder == null) return false; 3 // 入- 减一 4 // 出 加二 5 // 最后的总和应该是0 6 String[] nodes = preorder.split(","); 7 int degree = 1; 8 for (int i = 0; i < nodes.length; i++) { 9 degree -= 1; 10 if (degree < 0) return false; 11 if (!nodes[i].equals("#")) degree += 2; 12 } 13 return degree == 0; 14 }
以上是关于331. Verify Preorder Serialization of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
331. Verify Preorder Serialization of a Binary Tree
[栈] leetcode 331 Verify Preorder Serialization of a Binary Tree
LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree