二叉樹 (三)判斷是否是搜索二叉樹

搜索二叉樹:它或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別爲二叉排序樹

即 二叉搜索樹的中序遍歷一定是從小到大排好序的

所以判斷一棵樹是否是二叉搜索樹 查看其中序遍歷是否爲從小排到大的即可

修改非遞歸版本的中序遍歷代碼。設一個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));

	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章