zoukankan      html  css  js  c++  java
  • [LeetCode] 98. Validate Binary Search Tree Java

    题目:

    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.

    Example 1:

        2
       / 
      1   3
    

    Binary tree [2,1,3], return true.

    Example 2:

        1
       / 
      2   3
    

    Binary tree [1,2,3], return false.

    题意及分析:给出一课书,要求判断该树是不是二叉搜索树。二叉搜索树按照中序遍历得到的是一个升序序列,那么这道题只需要对树进行中序遍历即可,使用stack保存中间结果。这里需要注意的是理论最小值的获取,这里先获取最小值,然后当遍历到这个点时不需要做判断。

    代码:

    /**
     * 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) {
            if(root==null||(root.left==null&&root.right==null)) return true;
            TreeNode minNode = root;
            while(minNode.left!=null){
                minNode=minNode.left;
            }
            long nowMax=minNode.val;        //找到理论的最小值点
            Stack<TreeNode> stack = new Stack<>();
            TreeNode node = root;
            stack.add(node);
            while(node.left!=null||!stack.isEmpty()){
                if(node.left!=null){    //一直找到最左子节点
                    node = node.left;
                    stack.add(node);
                }else{      //输出该点,对栈当前点的右节点做相同操作
                    TreeNode now = stack.pop();
                    if(now!=minNode){
                        if(now.val>nowMax){  //如果当前大于遍历的上一个那么当前最大值编程当前点最大值
                            nowMax = now.val;
                        }else{      //按照中序遍历输出,结果当前输出比上一个数小,那么直接返回false
                            return false;
                        }
                    }
                    if(now.right!=null) {
                        node = now.right;
                        stack.add(node);        //将当前点加入stack中
                    }
                }
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    Spring中配置文件applicationContext.xml配置详解
    Web.xml配置详解
    linux基础命令学习(七)samba服务器配置
    linux基础命令学习(六)DHCP服务器配置
    linux基础命令学习五(软件包管理、下载管理)
    linux基础命令学习(四)计划任务
    linux上安装php
    linux上安装hadoop
    Redis(二)Jedis操作Redis
    Redis(一)简介及安装、测试
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7172124.html
Copyright © 2011-2022 走看看