[LeetCode/LinkedIn] Valid Binary Search Tree
来源:互联网 发布:芒果店长软件下载 编辑:程序博客网 时间:2024/06/16 19:11
Solution 1. In order Traversal
public boolean isValidBST(TreeNode root) { ArrayList<TreeNode> list = new ArrayList<TreeNode>(); inOrderBST(root,list); boolean start = true; int prev = 0; for(TreeNode node : list){ int i = node.val; if(start){ prev = i; start = false; }else { if(i<=prev){ return false; } prev = i; } } return true;}public void inOrderBST(TreeNode root, ArrayList list) { if (root == null) { return; } inOrderBST(root.left,list); list.add(root); inOrderBST(root.right,list);}
Solution 2. Advance In-order traversal
//global variable to keep the previous visited nodeprivate Node prev = null;public boolean isValidBST(Node root) { if (root == null) { return true; } if (!isValidBST(root.left)) { return false; } if (prev != null && root.val <= prev.val) { return false; } prev = root; return isValidBST(root.right);}
Solution 3:
//min & max value check approach//each iteration, current root being the min/maxpublic boolean isValidBST(Node root) { if (root == null) { return false; } //This will not work if the initial value is these two return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);}private boolean isValidBST(Node root, int min, int max) { if (root == null) { return true; } if (root.val > min && root.val < max) { return isValidBST(root.left, min, root.val) && isValidBST(root.right,root.val , max); } return false;}
0 0
- [LeetCode/LinkedIn] Valid Binary Search Tree
- leetcode-valid binary search tree
- 【Leetcode】Valid Binary Search Tree
- leetcode 94: Valid Binary Search Tree
- Valid Binary Search Tree
- [Leetcode]Binary Search Tree
- LeetCode: Validate Binary Search Tree
- LeetCode: Recover Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode: Recover Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Unique Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [leetcode] recover binary search tree
- [LeetCode] Validate binary search tree
- word中批量去掉某些符号
- 新手问题之找不到R文件
- 如何自定义RadioButton样式
- leetcode Binary Tree Postorder Traversal
- 小菜鸟带着梦想学chromium
- [LeetCode/LinkedIn] Valid Binary Search Tree
- SNAT、DNAT和MASQUERADE的含义
- /etc/fstab 文件解释
- 脚本渗透的概述
- PHP中的命名空间
- 二叉树的建立和遍历
- while、do-while、for、goto、递归五种方式求一个整数的位数
- Mac 上运行Hadoop的mapreduce报错exitCode: 127
- android应用安全——通信安全(android https)