面试题24:二叉搜索树的后序遍历序列
2015-10-02 16:39
405 查看
面试题24:二叉搜索树的后序遍历序列
题目描述:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
题目分析:
二叉搜索树的后序遍历有什么特点:最后一个值是根结点,左子树上的结点值都小于根结点的值,右子树上的结点值都大于根结点的值(题目已知任意两个数字都不相同)。
了解了这些,思路就有了,分别递归判断左右子树,递归关键是递归结束条件。
1. 我的实现
class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { if (sequence.size() == 0) return false; return Verify(sequence, 0, sequence.size() - 1); } bool Verify(vector<int> seq, int left, int right) { int mov; for (mov = left; mov < right; mov ++) if (seq[mov] > seq[right]) break; /* 如果只有左子树,则返回真 */ if (mov == right) return true; int pos = mov; for (;mov < right; mov ++) if (seq[mov] < seq[right]) break; /* 如果只有右子树,则返回真 */ if (pos == left && mov == right) return true; /* 如果是序列有错,则返回假 */ if (index < right) return false; /* 如果既有左子树又有右子树,则分别判断左右子树 */ return Verify(seq, left, pos - 1) && Verify(seq, pos, right - 1); } };
2. 《offer》上的解法
bool VerifyBST(int seq[], int len) { if (seq == 0 || len == 0) return false; int root = seq[len - 1]; int i; for (i = 0; i < len - 1; i ++) if (seq[i] > root) break; int j = i; for (; j < len - 1; j ++) if (seq[j] < root) return false; bool left = true; if (i > 0) left = Verify(seq, i); bool right = true; if (i < len - 1) right = Verify(seq + i, len - 1 - i); return (left && right); }
大同小异。
相关文章推荐
- Binary Search Tree Iterator,Reverse Nodes in k-Group
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Unique Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- 根据后序和中序遍历重建二叉树
- 根据后序和中序遍历重建二叉树
- Minimum Depth of Binary Tree
- Balanced Binary Tree
- Maximum Depth of Binary Tree
- LeetCode:Binary Search Tree相关题目合集
- LeetCode-Convert Sorted Array to Binary Search Tree
- 二叉搜索树的后序遍历
- poj2255 Tree Recovery 二叉树遍历
- 二叉树的遍历: 前序,中序,后序----非递归算法
- Convert Sorted Array(List) to Binary Search Tree
- Validate Binary Search Tree
- convert sorted array to binary search tree