“常用公式”在线计算,“设计手册”在线查询
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 分享淘帖 支持支持 反对反对

共 1 个关于本帖的回复 最后回复于 2013-7-30 17:35

沙发
孙宏雷 新来的 发表于 2013-7-30 17:35:24 | 只看该作者
研发埠培训中心
Good Answer:Note that it's not enough to write are cursive function that just checks if the left and right nodes of each node are less than and greater than the current node(and calls that recursively).You need to make sure that all the nodes of the subtree starting at your current node are within the valid range of values allowed by the current node's ancestors.Therefore you can solve this recursively by writing a helper function that accepts a current node,the smallest allowed value,and the largest allowed value for that subtree.An example of this is the following(in Java):boolean isValid(Node root) { return isValidHelper(root, Integer.MIN_VALUE,Integer.MAX_VALUE);}boolean isValidHelper(Node curr, int min,int max) { if(curr.left != null) { if(curr.left.value < min ||!isValidHelper(curr.left, min, curr.value)) return false; } if(curr.right != null) { if(curr.right.value > max ||!isValidHelper(curr.right, curr.value,max)) return false; } return true;}The running time of this algorithm is O(n).
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注我们

360网站安全检测平台