首页 > 其他 > 详细

面试题33. 二叉搜索树的后序遍历序列

时间:2020-05-09 16:08:37      阅读:52      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

BST的后序序列的合法序列是,对于一个序列S,最后一个元素是x (也就是根),如果去掉最后一个元素的序列为T,那么T满足:T可以分成两段,前一段(左子树)小于x,后一段(右子树)大于x,且这两段(子树)都是合法的后序序列。

 1 class Solution {
 2 public:
 3     bool verifyPostorder(vector<int>& postorder) 
 4     {
 5          if (postorder.empty())
 6          {
 7              return true;
 8          }
 9 
10          return judge(postorder, 0, postorder.size() -1);
11     }
12 
13     bool judge(vector<int> &a, int left, int right)
14     {
15         if(left >= right) 
16         {
17             return true;
18         }
19         
20         // 从后面开始找
21         int i = right;
22         while(i > left && a[i - 1] > a[right]) 
23         {
24             --i;     // 找到比根小的坐标
25         }
26         
27         // 从前面开始找 star到i-1应该比根小
28         for(int j = left; j < i - 1; ++j) 
29         {
30             if(a[j] > a[right]) 
31             {
32                 return false;
33             }
34         }
35         return judge(a, left, i - 1) && (judge(a, i,right - 1));
36     }
37 
38 };

 

面试题33. 二叉搜索树的后序遍历序列

原文:https://www.cnblogs.com/ocpc/p/12858022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!