0
点赞
收藏
分享

微信扫一扫

判断是否是查找二叉树

海牙秋天 2022-02-05 阅读 56
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
public class IsBST {
  public static class Node {
    public int value;
    public Node left;
    public Node right;

    Node(int value) { this.value = value; }
  }
  //是否是搜索二叉树
  //方式一
  public static boolean isBST(Node head) {
    if (head == null)
      return true;
    LinkedList<Node> inOrderList = new LinkedList<Node>();
    process(head, inOrderList);
    int pre = Integer.MIN_VALUE;
    for (Node cur : inOrderList) {
      if (pre >= cur.value) {
        return false;
      }
      pre = cur.value;
    }
    return true;
  }

  public static void process(Node node, LinkedList<Node> inOrderList) {
    if (node == null)
      return;
    process(node.left, inOrderList);
    inOrderList.add(node);
    process(node, inOrderList);
  }
  //方式二
  public static int prevalue = Integer.MIN_VALUE;
  public static boolean _isBST(Node head) {
    if (head == null)
      return true;
    boolean isLeftBST = _isBST(head.left);
    if (!isLeftBST)
      return false;
    if (head.value <= prevalue) {
      return false;
    } else {
      prevalue = head.value;
    }
    return _isBST(head.right);
  }
}
举报

相关推荐

0 条评论