zoukankan      html  css  js  c++  java
  • 判断二叉树是不是搜索二叉树

    /**
     *二叉搜索树
     *任何节点的左 子树不为null,则左子树上的所有的节点都比根节点小,右子树不为null,则右子树上的所有的节点都比根节点大
     *判断二叉搜索树的方法是:将树按照中序遍历后,是不是逐渐递增的
     *
     */
    public class SearchTree {
        
        public static void  main(String[] args) {
            
            Node root = new Node(4);
            root.left = new Node(2);
            root.right = new Node(5);
            root.left.left = new Node(1);
            root.left.right = new Node(3);
            root.right.right = new Node(6);
            System.out.println(isS(root));
            
        }
        
        /**
         * 中序遍历,      左子树 ->  根节点   ->  右子树
         * @param root
         */
        public static boolean isS(Node root) {
            boolean res = true;
            int pre = Integer.MIN_VALUE;
            boolean flag = false;
            Stack<Node> stack = new Stack<Node>();
            //从根节点开始,根节点的左节点,左节点的左节点依次入栈
            stack.push(root);
            while(root.left != null) {
                stack.push(root.left);
                root= root.left;
            }
            while(!stack.isEmpty()) {
                Node temp = stack.pop();
                if(temp != null) {
                    //栈顶元素出栈,打印该元素,
    //                System.out.print(temp.value + " ");
                    if(!flag) {
                        pre = temp.value;
                        flag = true;
                    }
                    if(temp.value - pre < 0) {
                        res = false;
                        break;
                    }
                    pre = temp.value;
                    //右子树不为空,右节点入栈
                    if(temp.right != null) {
                        Node n1 = temp.right;
                        //右节点入栈
                        stack.push(temp.right);
                        //右节点的左节点,左节点的左节点入栈
                        while(n1.left != null) {
                            stack.push(n1.left);
                            n1 = n1.left;
                        }
                    }
                }
            }
            return res;
        }
        
        public static class Node {
            Node left;
            Node right;
            int value;
            
            public Node(int value) {
                this.value = value;
            }
        }
    }
  • 相关阅读:
    require.js+bootstrap实现简单的页面登录和页面跳转
    require.js疑惑
    汉子转拼音(不支持多音字)
    require.js入门
    CSS+transform画动态表情
    nodejs的简单爬虫
    根据选择的省市区自动匹配邮政编码
    node将excel内容转json
    js实现省市区联动
    sql server 作业收缩数据库
  • 原文地址:https://www.cnblogs.com/moris5013/p/11670268.html
Copyright © 2011-2022 走看看