zoukankan      html  css  js  c++  java
  • [leetcode] Validate Binary Search Tree

    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.

    这个也算是基础题吧,目前经历过的所有关于树的问题,归根结底都是一个遍历的问题,BST是一个中序遍历的有序。最直接的想法很简单,直接中序遍历,储存每个值到一个list,然后遍历list检查是否有序。其实还好,2个O(N)还是O(N),还有额外空间开销。

    比较广泛的解法是下面这样:

    public class Solution {
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
    
        private boolean isValidBST(TreeNode root, int min, int max) {
            if (root == null)
                return true;
            if (root.val > min && root.val < max
                    && isValidBST(root.left, min, root.val)
                    && isValidBST(root.right, root.val, max)) {
                return true;
            } else {
                return false;
            }
        }
    }

    这个解法是参考stackoverflow做出的,自己写的代码没有这么优雅,但是基本思路一致。遍历的过程中可以实时检查当前node的值。所以引入变量才是王道。

    什么时候要研究一下,到底怎么样把递归转为循环,引入一个stack?

  • 相关阅读:
    机器学习--避免过度拟合 笔记
    《机器学习》第三章 决策树学习 笔记加总结
    《机器学习》第二章 概念学习和一般到特殊序
    《机器学习》第一章 引言 笔记加总结
    jmeter+ant生成html报告
    jmeter之beanshell使用
    html常用标签
    css样式
    fiddler设置重定向
    fiddler设置断点
  • 原文地址:https://www.cnblogs.com/t--c---/p/3783112.html
Copyright © 2011-2022 走看看