剑指offer:面试题33. 二叉搜索树的后序遍历序列
生活随笔
收集整理的這篇文章主要介紹了
剑指offer:面试题33. 二叉搜索树的后序遍历序列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:二叉搜索樹的后序遍歷序列
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的后序遍歷結果。如果是則返回?true,否則返回?false。假設輸入的數組的任意兩個數字都互不相同。
參考以下這顆二叉搜索樹:
? ? ?5
? ? / \
? ?2 ? 6
? / \
?1 ? 3
示例 1:
輸入: [1,6,3,2,5]
輸出: false
示例 2:
輸入: [1,3,2,6,5]
輸出: true
提示:數組長度 <= 1000
解題:
方法一:遞歸
已知條件: 后序序列最后一個值為root;二叉搜索樹左子樹的值都比root小,右子樹的值都比root大。
步驟:
- 確定根節點root;
- 遍歷序列(除去root結點),找到第一個大于root的位置,則該位置左邊為左子樹,右邊為右子樹;
- 遍歷右子樹,若發現有小于root的值,則直接返回false;
- 分別判斷左子樹和右子樹是否仍是二叉搜索樹(即遞歸步驟1、2、3)。
class Solution {
public:bool verifyPostorder(vector<int>& postorder) {bool res = true;if (postorder.empty())return res;res = helper(postorder,0,postorder.size()-1);return res;}bool helper(vector<int>& postorder, int start, int end){if (postorder.empty() || start > end)return true;//根結點int root = postorder[end];//在二叉搜索樹中左子樹的結點小于根結點int i = start;for(;i<end;i++){if (postorder[i] > root)break;}//在二叉搜索書中右子樹的結點大于根結點for(int j = i;j<end;j++){if (postorder[j] < root)return false;}//判斷左子樹是不是二叉搜索樹bool left = true;if (i>start){left = helper(postorder,start,i-1);}//判斷右子樹是不是二叉搜索樹bool right = true;if (i<end-1){right = helper(postorder, i,end-1);}return left && right;}
};
方法二:
class Solution {bool helper(vector<int>& post,int lo, int hi){if(lo >= hi) return true; //單節點或空節點返回trueint root = post[hi]; //后序遍歷序列最后的值為根節點的值int l = lo;while(l<hi && post[l]<root) l++; //遍歷左子樹(值小于根),左子樹序列post[lo, l);int r = l;while(r<hi && post[r]>root)r++; //遍歷右子樹(值大于根),右子樹序列post[l, r);if(r != hi) return false;//若未將post[l, hi)遍歷完,則非后序遍歷序列 返回falsereturn helper(post, lo, l-1) && helper(post, l, hi-1); //遞歸檢查左右子樹}
public:bool verifyPostorder(vector<int>& postorder) {return helper(postorder,0,postorder.size()-1);}
};
總結
以上是生活随笔為你收集整理的剑指offer:面试题33. 二叉搜索树的后序遍历序列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer:面试题32 - III.
- 下一篇: 剑指offer:面试题34. 二叉树中和