ideas
What is a binary search tree
It can be seen that in a binary tree:
- If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
- If the right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
- The left and right subtrees of any node are also binary search trees respectively;
- There are no nodes with equal keys.
The topic is to judge whether a sequence is a legal post-order traversal sequence of a binary search tree.
Recursion + post-order traversal simulation of tree
topic
Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree.
Returns true if so, false otherwise.
Suppose any two numbers of the input array are different from each other.
data range
Array length [0,1000]
.
Sample
Input: [4, 8, 6, 12, 16, 14, 10]
output: true
java code
class Solution {
private int [] seq;
public boolean dfs(int l, int r)
{
if (l >= r) return true;
int root = seq[r];
int k = l;
while (k < r && seq[k] < root) k++;
for (int i = k; i < r; i++)
if (seq[i] < root) // 右边应该都比root大
return false;
// 递归处理左右两边
return dfs(l, k - 1) && dfs(k, r - 1);
}
public boolean verifySequenceOfBST(int [] sequence) {
seq = sequence;
return dfs(0, seq.length -1);
}
}