标签:tree 二叉搜索树 span push res bsp public root blog
版本1:C++
class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { if (sequence.size() == 0) return false; int len = sequence.size(),i = 0,j; int root = sequence[len - 1]; // 根节点 vector<int> leftTree, rightTree; while (sequence[i] < root){ // 找出左子树的范围 0 ~ i-1 leftTree.push_back(sequence[i]); // 将左子树存入一个vector i++; } for (j = i; j < len - 1; j++){ // 在右子树的范围 j ~ len-1 内判断有没有不合理的数字 if (sequence[j] < root){ return false; } rightTree.push_back(sequence[j]); // 将右子树存入一个vector } bool resofleft = true, resofright = true; // 这里的初始化重要,是控制判断为真情况的 if (leftTree.size() > 0){ // 保证子树为空时能够跳过判断 resofleft = VerifySquenceOfBST(leftTree); // 递归判断左子树 } if (rightTree.size() > 0){ resofright = VerifySquenceOfBST(rightTree); // 递归判断右子树 } return (resofleft && resofright); // 左右子树都返回为真时,才为真 } };
标签:tree 二叉搜索树 span push res bsp public root blog
原文地址:http://www.cnblogs.com/simplepaul/p/7007612.html