zoukankan      html  css  js  c++  java
  • 判断树是否为搜索树

    搜索树:左节点小于中间节点,中间节点大于右边节点

    思路:利用中序遍历

    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;
            }
        }
    }
  • 相关阅读:
    云计算
    uc/xi
    互联网 2.0概念
    java连接数据库
    记录一下安装 mysql 的踩坑之路
    1
    Linux介绍与基本必知命令
    Web课程Linux命令统计
    7——条件判断、三目运算、条件循环、迭代循环
    6——散列类型、运算符优先级、逻辑运算
  • 原文地址:https://www.cnblogs.com/zhaolei1996/p/12456417.html
Copyright © 2011-2022 走看看