leetcode--98. Validate Binary Search Tree
阿新 • • 發佈:2017-09-01
ont rip != 判斷 邊界 ems nbsp mine 最大
1、問題描述
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.
2、邊界條件:root==null?
3、思路:1)二叉搜索數的性質,先序遍歷就是一個升序排列方式。利用這個性質,先序遍歷樹得到一個數組,然後判斷數組是否為升序排列。可以在最終數組判斷,也可以遍歷一個子樹就判斷。
2)一個節點的值就限制了它的左子樹的最大值,右子樹的最小值。這樣節點的信息就可以向下傳遞。
4、代碼實現
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * }*/ class Solution { public boolean isValidBST(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); preOrder(result, root); if (result.size() <= 1) { return true; } for (int i = 0; i < result.size() - 1; i++) {if (result.get(i) >= result.get(i + 1)) { return false; } } return true; } public void preOrder(List<Integer> result, TreeNode root) { if (root == null) { return; } preOrder(result, root.left); result.add(root.val); preOrder(result, root.right); } }
錯誤做法:對於一個節點,判斷val是否大於left,小於right;然後判斷子樹是否為BST。這樣判斷只是確定了3個值的關系,並沒有確定節點和子樹的關系。[10,5,15,null,null,6,20]不通過。
class Solution { public boolean isValidBST(TreeNode root) { if (root == null) { return true; } if (root.left != null && root.left.val >= root.val) { return false; } if (root.right != null && root.right.val <= root.val) { return false; } return isValidBST(root.left) && isValidBST(root.right); } }
在遞歸過程中判斷每個子樹是否為BST,這種方式也能實現,但是時間復雜度不能保證,大部分情況比較慢。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); return preOrder(result, root); } public boolean preOrder(List<Integer> result, TreeNode root) { if (root == null) { return true; } if (!preOrder(result, root.left)) { return false; } result.add(root.val); if (!preOrder(result, root.right)) { return false; } if (result.size() <= 1) { return true; } for (int i = 0; i < result.size() - 1; i++) { if (result.get(i) >= result.get(i + 1)) { return false; } } return true; } }
方法二---推薦
class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public boolean isValidBST(TreeNode root, int minVal, int maxVal) { if (root == null) { return true; } if (root.val <= minVal || root.val >= maxVal) { return false; } return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal); } }
5、時間復雜度:遍歷一遍樹O(N), 空間復雜度:O(N),數組
6、api
leetcode--98. Validate Binary Search Tree