Validate Binary Search Tree
来源:互联网 发布:windows徽标键不能用 编辑:程序博客网 时间:2024/06/08 20:07
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.
A single node tree is a BST
分析:此题需要注意的是一个平衡二叉树的条件为左子树的val中最大的值需要小于root.val,右子树的val最小值需要大于root.val,一旦有任意子树不满足上述条件,则该树不是平衡二叉树。
class ResultType { boolean isValid; int max; int min; ResultType(boolean a, int b, int c) { isValid = a; max = b; min = c; }}public class Solution { /** * @param root: The root of binary tree. * @return: True if the binary tree is BST, or false */ public boolean isValidBST(TreeNode root) { ResultType rt = helper(root); return rt.isValid; } private ResultType helper(TreeNode root) { if (root == null) { return new ResultType(true, Integer.MIN_VALUE, Integer.MAX_VALUE); } ResultType left = helper(root.left); ResultType right = helper(root.right); if (!left.isValid || !right.isValid) { return new ResultType(false, 0, 0); } if ((root.left != null && left.max >= root.val) || (root.right != null && right.min <= root.val)) { return new ResultType(false, 0, 0); } return new ResultType(true, Math.max(root.val, right.max), Math.min(root.val, left.min)); }}
0 0
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- centos7安装python的MySQLdb模块
- fatal error LNK1112: 模块计算机类型“X86”与目标计算机类型“x64”冲突-解决
- class VS struct
- go []Type(数组) 无法直接转化为 []interface{}(can't I assign any slice to an []interface{})
- 有关人工智能
- Validate Binary Search Tree
- Android开发 Handler MessageQueue Looper消息循环原理分析
- 墨妈的教学笔记之《数据压缩》开播啦
- Hadoop2.7.3+Spark2.1.0 完全分布式环境 搭建全过程
- OD的hit跟踪和run跟踪
- iOS开发-AFNetworking/NSURLSession异步处理
- [Azure]使用Azure Powershell输出ARM模式下某个账号中所有订阅下的虚拟网络拓扑
- qt学习之路九(QString、string和char*之间的转换)
- 回文素数