F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[剑指offer] 二叉搜索树的后序遍历序列

二叉搜索树的后序遍历序列 P157

题目:输入一个数组,判断这个数组是不是一个二叉搜索树的后序遍历的结果。

solution:我们知道后序遍历序列的最后一个item是根节点,如果确实是二叉搜索树的后序遍历结果,那么在[0,N-2]中一定存在一个位置k,满足:

[0,K]的元素都是小于item的,[K+1,N-1]的元素都是大于item的。如果不存在这样的节点,那么说明不是二叉搜索树的后序遍历的结果。

isValid-postorder-travel(int [] nums,int start,int end):

  if(start>=end) return true;

  int mid = nums[end];

  int index = start;

  while(index<=end&&nums[index]<mid) index++;

  int midindex = index;

  while(index<=end&&nums[index]>mid) index++;

  if(nums[index]<=mid) return false;

  boolean res1 = isValid-postorder-travel(nums,start,midindex-1);

  if(res1==false)  return false;

  boolean res2 = isValid-postorder-travel(nums,midindex,end-1);

  return res2;

 

posted on 2015-09-04 15:56  F_G  阅读(133)  评论(0编辑  收藏  举报