判断整数序列是不是二元查找树的后序遍历结果
2013-09-26 20:13
411 查看
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。 例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果: 8 / \ 6 10 / \ / \ 5 7 9 11 因此返回true。 如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
// Verify whether a squence of integers are the post order traversal // of a binary search tree (BST) // Input: squence - the squence of integers // length - the length of squence // Return: return ture if the squence is traversal result of a BST, // otherwise, return false bool verifySquenceOfBST(int squence[], int length) { if(squence == NULL || length <= 0) return false; // root of a BST is at the end of post order traversal squence int root = squence[length - 1]; // the nodes in left sub-tree are less than the root int i = 0; for(; i < length - 1; ++ i) { if(squence[i] > root) break; } // the nodes in the right sub-tree are greater than the root int j = i; for(; j < length - 1; ++ j) { if(squence[j] < root) return false; } // verify whether the left sub-tree is a BST bool left = true; if(i > 0) left = verifySquenceOfBST(squence, i); // verify whether the right sub-tree is a BST bool right = true; if(i < length - 1) right = verifySquenceOfBST(squence + i, length - i - 1); return (left && right); }
相关文章推荐
- MS100(9)-判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 第9 题 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- IT公司100题-9-判断整数序列是不是二元查找树的后序遍历结果
- 算法讨论(五)--判断整数序列是不是二元查找树的后序遍历结果
- 9、判断整数序列是不是二元查找树的后序遍历结果
- 微软,Google面试题 (6) —— 判断整数序列是不是二元查找树的后序遍历结果
- 【转载】判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 面试题:判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试100题之六,判断整数序列是不是二元查找树的后序遍历结果
- flag5判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 100题_06 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果