题目描述
请实现一个函数,检查一棵二叉树是否为二叉查找树。
给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。
import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ public class Checker { public boolean checkBST(TreeNode root) { // write code here //二叉排序树 中序遍历是有序的 //树的遍历若采用非递归的方法,就要采用栈去模拟实现 return inOrder(root); } public boolean inOrder(TreeNode root){ int[] a = new int[1000]; int count = 0; Stack<TreeNode> stack = new Stack<TreeNode>(); while((root != null) || (!stack.isEmpty())){ while(root != null){ stack.push(root); root = root.left; } a[count++] = stack.pop().val; if(!stack.isEmpty()){ root = stack.peek(); root = root.right; a[count++] = stack.pop().val; } } for (int i = 0; i < count-1; i++){ if(a[i] > a[i+1]){ return false; } } return true; } }