CC4.5 检测二叉查找树

<div class="para" style="color: rgb(51, 51, 51); margin: 15px 0px 5px; text-indent: 2em; line-height: 24px; font-family: arial, 宋体, sans-serif; font-size: 14px;">二叉排序树或者是一棵空树,或者是具有下列性质的<a target=_blank target="_blank" href="http://baike.baidu.com/view/88806.htm" style="text-decoration: none; color: rgb(19, 110, 194);">二叉树</a>:</div><div class="para" style="color: rgb(51, 51, 51); margin: 15px 0px 5px; text-indent: 2em; line-height: 24px; font-family: arial, 宋体, sans-serif; font-size: 14px;">(1)若左子树不空,则左子树上所有结点的值均小于它的<a target=_blank target="_blank" href="http://baike.baidu.com/view/390474.htm" style="text-decoration: none; color: rgb(19, 110, 194);">根结</a>点的值;</div><div class="para" style="color: rgb(51, 51, 51); margin: 15px 0px 5px; text-indent: 2em; line-height: 24px; font-family: arial, 宋体, sans-serif; font-size: 14px;">(2)若右子树不空,则右子树上所有结点的值均大于或<strong>等于</strong>它的根结点的值;</div><div class="para" style="color: rgb(51, 51, 51); margin: 15px 0px 5px; text-indent: 2em; line-height: 24px; font-family: arial, 宋体, sans-serif; font-size: 14px;">(3)左、右子树也分别为二叉排序树;</div><div class="para" style="color: rgb(51, 51, 51); margin: 15px 0px 5px; text-indent: 2em; line-height: 24px; font-family: arial, 宋体, sans-serif; font-size: 14px;">(4)没有键值相等的节点。</div>
public static int LAST_VALUE=INTEGER.MIN_VALUE;
public boolean checkBST(TreeNode root)
{
  if(root == null)
    return true; 
  if(!checkBST(root.left)) return false;
  
  if(root.val < LAST_VALUE)
    return false;
  else 
    LAST_VALUE = root.val;
	
  if(!checkBST(root.right)) return false;
  
  return true;
}

1.第一种递归方法

中序遍历的结果应该是有序的,这里使用递归的方法,先检测当前node的左子树是否是有序的(需要借助一个LAST_VALUE来存储当前检查到的值),然后我们再比较一下当前node的val是否>=左子树中最大的节点(与LAST_VALUE)作比较。之后再递归与右子树进行比较。如果检查完成没有问题,则这个节点可以返回true

这种方法不能检测有重复值的二叉搜索树的正确性

2.

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/wangyuesong2/article/details/43851175
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞