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;
            }
        }
    }
  • 相关阅读:
    C语言 · 报时助手
    C语言 · 完美的代价
    C语言 · 十六进制转八进制
    C语言 · 十六进制转十进制
    C语言 · 芯片测试
    C语言 · 素数求和
    C语言 · 五次方数
    Lodop多分出空白页的可能(情况1)
    C-Lodop提示“网页还没下载完毕,请稍等一下再操作.”
    Lodop简答问答大全
  • 原文地址:https://www.cnblogs.com/zhaolei1996/p/12456417.html
Copyright © 2011-2022 走看看