题目
地址:https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd
思路
- 根节点的值大于左子树小于右子树
- 后序遍历: 左子树 -> 右子树 -> 根节点
关键:最后一个元素是根节点,找到他的左子树和右子树,递归判断。
Golang 代码
package main
import "fmt"
func main() {
fmt.Printf("VerifySquenceOfBST([]int{5, 7, 6, 9, 11, 10, 8})=%#v\n", VerifySquenceOfBST([]int{5, 7, 6, 9, 11, 10, 8}))
fmt.Printf("VerifySquenceOfBST([]int{7,4,5,6})=%#v\n", VerifySquenceOfBST([]int{7, 4, 5, 6}))
}
func VerifySquenceOfBST(sequence []int) bool {
if sequence == nil || len(sequence) <= 0 {
return false
}
length := len(sequence)
root := sequence[length-1]
//get left tree
l := 0
for ; l < length-1; l++ {
if root < sequence[l] {
break
}
}
//verify right tree.
r := l
for ; r < length-1; r++ {
if root > sequence[r] {
return false
}
}
left := true
if l > 0 {
left = VerifySquenceOfBST(sequence[:l])
}
right := true
if r < length-1 {
right = VerifySquenceOfBST(sequence[l:length])
}
return left && right
}
C 代码
#include <stdio.h>
#define bool int
#define true 1
#define false 0
//reference:https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd
bool verify_post_BST(int seq[], int len) {
if (seq == NULL || len <= 0) {
return false;
}
int root = seq[len - 1];
//get left tree
int l = 0;
for (; l < len - 1; l++) {
if (root < seq[l]) {
break;
}
}
//get right tree.
int r = l;
for (; r < len - 1; r++) {
if (root > seq[r]) {
return false;
}
}
bool left = true;
if (l > 0) {
left = verify_post_BST(seq, l);
}
bool right = true;
if (r < len - 1) {
right = verify_post_BST(seq + l, len - l - 1);
}
return left && right;
}
int main() {
int seq1[] = {5, 7, 6, 9, 11, 10, 8};
bool r1 = verify_post_BST(seq1, 7);
int seq2[] = {7,4,5,6};
bool r2 = verify_post_BST(seq2, 4);
printf("r1=%d\n", r1);
printf("r2=%d\n", r2);
return 0;
}