zoukankan      html  css  js  c++  java
  • LeetCode -- Validate Binary Search Tree

    Question:

    Given a binary tree, determine if it is a valid binary search tree (BST).

    Assume a BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than the node's key.
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • Both the left and right subtrees must also be binary search trees.

    Analysis:

    给出一棵二叉树,判断它是否是二叉搜索树(BST)。

    假设BST是这样定义的:它要么是一棵空树,要么是具有以下性质的树:

    1)左子树的所有结点的关键码小于根节点的关键码;

    2)右子树的所有结点的关键码大于根节点的关键码;

    3)左子树和右子树也是二叉搜索树。

    思路:对于一棵BST来说,它的中序遍历的值正好是从大到小排列的,因此可以根据中序遍历来判断二叉树是否是BST。

    Answer:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            List<Integer> l = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode p = root;
            do {
                while(p != null) {
                    stack.push(p);
                    p = p.left;
                }
                if(!stack.isEmpty()) {
                    p = stack.pop();
                    if(l.size() != 0) {
                        if(p.val <= l.get(l.size()-1))
                            return false;
                    }
                    l.add(p.val);
                    p = p.right;
                }
            } while(p != null || !stack.isEmpty());
            return true;
        }
    }
  • 相关阅读:
    THINKPHP增删改查--(改)
    thinkphp中各字母代表的发放和具体实例
    PHP时间戳和日期互转换
    jquery方法大全
    Bootstrap里的文件分别表示什么?都有什么用?
    文本一处隐藏显示
    点击下拉,其余不动的jquery事件(转)
    JQuery中$.ajax()方法参数详解
    数据库联合查询输出数量
    如何使div居中
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5234736.html
Copyright © 2011-2022 走看看