題目:java
Given a binary tree, determine if it is a valid binary search tree (BST).node
Assume a BST is defined as follows:編程
連接:http://leetcode.com/problems/validate-binary-search-tree/less
題解:學習
一開始使用的是BST定義,結果遇到一些邊界條件會出問題,好比 Integer.MAX_VALUE, #,Integer.MAX_VALUE一類的。因此最後仍是使用了recursive的in-order traversal。 代碼依然參考了discussion, 本身要勤練習。spa
Time Complexity - O(n), Space Complexity - O(1)code
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode lastNode; public boolean isValidBST(TreeNode root) { if(root == null) return true; if(!isValidBST(root.left)) return false; if(lastNode != null && lastNode.val >= root.val) return false; lastNode = root; if(!isValidBST(root.right)) return false; return true; } }
另 - 今天去看了一部電影叫<The Martian>,很好看,講的是馬特戴蒙扮演的航天員在火星受困最後被成功救助的故事。即便孤身一人身處險境,也不能放棄但願, 因此要好好學習編程,爲人類航空航天事業作貢獻(假如還來得及的話)。blog
二刷:leetcode
和一刷同樣的方法,先創建一個輔助節點,再用in-order traversal遍歷整個樹而且進行判斷get
Java:
Time Complexity - O(n), Space Complexity - O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private TreeNode lastNode; public boolean isValidBST(TreeNode root) { if (root == null) { return true; } if (!isValidBST(root.left)) { return false; } if (lastNode != null && lastNode.val >= root.val) { return false; } lastNode = root; if (!isValidBST(root.right)) { return false; } return true; } }
三刷:
Java:
Time Complexity - O(n), Space Complexity - O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode prev; public boolean isValidBST(TreeNode root) { if (root == null) return true; if (!isValidBST(root.left)) return false; if (prev != null && prev.val >= root.val) return false; prev = root; if (!isValidBST(root.right)) return false; return true; } }
Reference:
https://leetcode.com/discuss/37320/o-1-space-java-solution-morris-in-order-traversal
https://leetcode.com/discuss/45425/c-simple-recursive-solution
https://leetcode.com/discuss/39567/simple-java-recursion-solution
https://leetcode.com/discuss/22234/my-java-inorder-iteration-solution
https://leetcode.com/discuss/27913/accepted-java-solution