Valid Ordered Tree
Valid preorder tree
Given an ArrayList of Nodes, with each Node having an ID and a parent ID, determine whether the List is given in preorder.
parent set store the parentID
Except root node, general node's parentID will be traversed and stored in parent set.
255. Verify Preorder BST
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
Use a stack to store the traversed left tree, if p smaller than last pushed number, then we still in the left tree. Otherwise, pop all the node in stack if we are in right tree. Take the last poped number as upper bound
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 #
using a stack, scan left to right
case 1: we see a number, just push it to the stack
case 2: we see #, check if the top of stack is also #, if so, pop #, pop the number in a while loop, until top of stack is not #
in the end, check if stack size is 1, and stack top is #
Last updated
Was this helpful?