zoukankan      html  css  js  c++  java
  • 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.

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

     

    解决思路

    1. 递归:当前节点的值 与 左节点的最右子节点(左子树最大的节点)、右节点的最左子节点(右子树最小的节点) 比较;

    2. 非递归中序遍历(前后指针);

    方法1较方法2有较多的重复计算,方法2的时间复杂度为O(n).

     

    程序

    1. 递归

    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if (root == null) {
                return true;
            }    
            
            long leftMax = getLeftMax(root.left);
            long rightMin = getRightMin(root.right);
            if (leftMax >= root.val || rightMin <= root.val) {
                return false;
            }
            
            return isValidBST(root.left) && isValidBST(root.right);
        }
        
        private long getLeftMax(TreeNode root) {
            if (root == null) {
                return Long.MIN_VALUE;
            }
            TreeNode node = root;
            while (node.right != null) {
                node = node.right;
            }
            return (long)node.val;
        }
        
        private long getRightMin(TreeNode root) {
            if (root == null) {
                return Long.MAX_VALUE;
            }
            TreeNode node = root;
            while (node.left != null) {
                node = node.left;
            }
            return (long)node.val;
        }
    }
    

    2. 非递归中序遍历

    public class Solution {
        // inorder traversal, two pointers
        public boolean isValidBST(TreeNode root) {
            if (root == null) {
                return true;
            }    
            Stack<TreeNode> s = new Stack<>();
            TreeNode node = root;
            TreeNode pre = null;
            
            while (node != null || !s.isEmpty()) {
                while (node != null) {
                    s.push(node);
                    node = node.left;
                }
                if (!s.isEmpty()) {
                    TreeNode cur = s.pop();
                    if (pre != null && pre.val >= cur.val) {
                        return false;
                    }
                    pre = cur;
                    node = cur.right;
                }
            }
            
            return true;
        }
    }
    
  • 相关阅读:
    蜂窝网格的坐标以及寻路
    unity3d 第三人称视角的人物移动以及相机控制
    基本HTML结构
    平衡二叉树
    STL基础复习
    递归
    unity 傅老师学习
    blender基础操作
    最小生成树
    最短路径
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4723506.html
Copyright © 2011-2022 走看看