二叉树 (三)判断是否是搜索二叉树

搜索二叉树:它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树

即 二叉搜索树的中序遍历一定是从小到大排好序的

所以判断一棵树是否是二叉搜索树 查看其中序遍历是否为从小排到大的即可

修改非递归版本的中序遍历代码。设一个pre用来保存上一次的节点 在输出位置判断pre是否大于此应该输出的节点

public static boolean isBST(Node head) {
		if (head == null)
			return true;
		Stack<Node> stack = new Stack<Node>();
		int pre=Integer.MIN_VALUE;
		while (!stack.isEmpty()||head!=null) {
			while (head != null) {
				stack.push(head);
				head = head.left;
			}
			head = stack.pop();
			if(head.value <pre) return false;
			//System.out.print(head.value+" ");
			pre=head.value;
			head = head.right;
		}
		return true;
	}   

在此暂时收录一个方法二:木的解析...

	public static boolean isBST2(Node head) {
		if (head == null) {
			return true;
		}
		boolean res = true;
		Node pre = null;
		Node cur1 = head;
		Node cur2 = null;
		while (cur1 != null) {
			cur2 = cur1.left;
			if (cur2 != null) {
				while (cur2.right != null && cur2.right != cur1) {
					cur2 = cur2.right;
				}
				if (cur2.right == null) {
					cur2.right = cur1;
					cur1 = cur1.left;
					continue;
				} else {
					cur2.right = null;
				}
			}
			if (pre != null && pre.value > cur1.value) {
				res = false;
			}
			pre = cur1;
			cur1 = cur1.right;
		}
		return res;
	}

完整测试代码:

package BinaryTree;

import java.util.Stack;

import BinaryTree.threePrintTree.Node;

//判断一个数是不是二叉搜索树
public class SerchTree {

	
	
	
	public static boolean isBST(Node head) {
		if (head == null)
			return true;
		Stack<Node> stack = new Stack<Node>();
		int pre=Integer.MIN_VALUE;
		while (!stack.isEmpty()||head!=null) {
			while (head != null) {
				stack.push(head);
				head = head.left;
			}
			head = stack.pop();
			if(head.value <pre) return false;
			//System.out.print(head.value+" ");
			pre=head.value;
			head = head.right;
		}
		return true;
	}   
	public static boolean isBST2(Node head) {
		if (head == null) {
			return true;
		}
		boolean res = true;
		Node pre = null;
		Node cur1 = head;
		Node cur2 = null;
		while (cur1 != null) {
			cur2 = cur1.left;
			if (cur2 != null) {
				while (cur2.right != null && cur2.right != cur1) {
					cur2 = cur2.right;
				}
				if (cur2.right == null) {
					cur2.right = cur1;
					cur1 = cur1.left;
					continue;
				} else {
					cur2.right = null;
				}
			}
			if (pre != null && pre.value > cur1.value) {
				res = false;
			}
			pre = cur1;
			cur1 = cur1.right;
		}
		return res;
	}
	public static void main(String[] args) {
		Node head = new Node(4);
		head.left = new Node(2);
		head.right = new Node(6);
		head.left.left = new Node(1);
		head.left.right = new Node(3);
		head.right.left = new Node(5);

		//printTree(head);
		System.out.println(isBST2(head));
		//System.out.println(isCBT(head));

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值