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.
Example 1:

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

Example 2:

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

思路

  1. 用一个ResultStruct, 包含:
    • isBST:表示以当前node为根节点的树是否为BST:
    • minValue:表示以当前node为根节点的树,其最小的node值
    • maxValue:表示以当前node为根节点的树,其最大的node值
  2. 从root开始遍历,每个节点均返回这个结构:
    • root 为空时,其结构为(true, Integer. MAX_VALUE, Integer.MIN_VALUE)
    • 向下遍历其左右子节点,看其左右子节点返回的结构,是否有isBST == false,如果有,返回结构为(false,0,0)
    • 如果其左child的maxValue >= root.val, 或者右child的minValue <= root.val,说明当前节点不是BST,同样返回结构为(false,0,0)
    • 如果以上都不满足,那么说明其是一个BST,返回结构为true,同时返回其最大和最小node的值
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private class helpStruct {
        private boolean isBST;
        private int min;
        private int max;
        public helpStruct(boolean isBST, int min, int max) {
            this.isBST = isBST;
            this.min = min;
            this.max = max;
        }
    }
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        return helper(root).isBST;
    }
    
    private helpStruct helper(TreeNode root) {
        if (root == null) {
            return new helpStruct(true, Integer.MAX_VALUE, Integer.MIN_VALUE);
        }
        
        helpStruct left = helper(root.left);
        helpStruct right = helper(root.right);
        
        if (!left.isBST || !right.isBST) {
            return new helpStruct(false, 0, 0);
        }
        
        if ((root.left != null && left.max >= root.val) || (root.right != null && right.min <= root.val)) {
            return new helpStruct(false, 0, 0);
        }
        
        return new helpStruct(true, Math.min(root.val, left.min), Math.max(root.val, right.max)); 
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容