Validate Binary Search Tree - Leetcode
来源:互联网 发布:linux ping 停止 编辑:程序博客网 时间:2024/06/10 14:23
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isValidBST(TreeNode root) { Stack<TreeNode> s = new Stack<>(); ArrayList<Integer> ai = new ArrayList<>(); TreeNode pointer = root; while(pointer!=null || !s.empty()){ if(pointer!=null){ s.push(pointer); pointer=pointer.left; }else{ int pre = s.peek().val; if(ai.size()>=1 && pre<=ai.get(ai.size()-1)) return false; ai.add(pre); pointer=s.pop().right; } } return true; } }
中序遍历一棵树,看看是否有打破递增的规律。
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
. 0 0
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode | Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- 从C到OC的转变
- Java 理论与实践: 用动态代理进行修饰(可以借鉴到spring的学习)
- 毕业五年决定你的一生
- 接口 ResultSetMetaData
- android常用属性设置
- Validate Binary Search Tree - Leetcode
- android常用控件属性
- 找寻·第二个青春·14年总
- Code[VS] 1004 四子连棋
- apache commons包 简要介绍
- 06. 解空间
- 详谈排序算法之选择类排序(两种方法实现堆排序)
- Altium Designe 原理图转成PCB时候出现很多unknown pin
- javaWeb 项目Tomcat启动报404