判断树是否为搜索树
搜索树:左节点小于中间节点,中间节点大于右边节点
思路:利用中序遍历
import java.util.ArrayList; import java.util.List; public class Main { private static void temp(Node tree,List<Integer> list){ if(tree == null){ return ; } temp(tree.left,list); list.add(tree.value); temp(tree.right,list); } public static boolean binarySearchTree(Node tree){ List<Integer> list = new ArrayList<Integer>(); temp(tree,list); for(int i=0;i<list.size()-1;i++){ if(list.get(i)>list.get(i+1)){ return false; } } return true; } public static void main(String[] args) { Node tree = new Node(5); Node left = new Node(7); Node right = new Node(6); tree.left = left; tree.right = right; System.out.println(binarySearchTree(tree)); } static class Node{ int value; Node left; Node right; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public Node(int value, Node left, Node right) { this.value = value; this.left = left; this.right = right; } public Node(int value) { this.value = value; } } }
心有多大,天有多高,一起奋斗!!