Solution 9: 判断序列是否为BST的后续遍历结果

问题描述

输入一个整数序列,判断该序列是否为一颗BST的后序遍历序列。

解决思路

递归:

(1) 序列的最后一个元素为根节点元素;

(2) 在序列中找出前一段代表根节点的左子树孩子们,而剩下的一段为右子树孩子们,检查这些节点的值是否都是大于(等于根节点元素)。

(3) 然后递归的对两部分进行判断。

程序

public class IsPostorderSequence {
	public boolean isPostorderSeq(int[] nums) {
		if (nums == null || nums.length == 0) {
			return true;
		}

		return helper(nums, 0, nums.length - 1);
	}

	private boolean helper(int[] nums, int begin, int end) {
		if (begin >= end) {
			return true;
		}

		int rootVal = nums[end];
		int i = 0;
		for (; i < end; i++) {
			// find left nodes
			if (nums[i] > rootVal) {
				break;
			}
		}

		for (int j = i; j < end; j++) {
			// check right nodes
			if (nums[j] <= rootVal) {
				return false;
			}
		}

		return helper(nums, 0, i - 1) && helper(nums, i, end - 1);
	}
}
原文地址:https://www.cnblogs.com/harrygogo/p/4615231.html