面试题-判断树是否为搜索树

面试题-判断树是否为搜索树

搜索树:左节点小于中间节点,中间节点大于右边节点 思路:利用中序遍历

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(Noderight){
            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;
        }
    }
}

天天踏实过,步步踏实做!——————————Mrgao

原文链接:https://www.mrgaocloud.com/?p=1404,转载请注明出处。
0

评论0

请先

站点公告

欢迎使用红狐网!红狐弹幕播放器已更新新版V1.7.2!立即查看
显示验证码
没有账号?注册  忘记密码?

社交账号快速登录