leetcode -- Validate Binary Search Tree

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.

[解题思路]

1.中序遍历BST得到的是一个有序的结果,遍历该结果如果出现前面数字比后面大的则说明不是BST

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isValidBST(TreeNode root) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         if(root == null){
15             return true;
16         }
17         ArrayList<Integer> elems = new ArrayList<Integer>();
18         inOrderTraverse(root, elems);
19         boolean result = true;
20         for(int i = 1; i < elems.size(); i++){
21             if(elems.get(i - 1) >= elems.get(i)){
22                 result = false;
23                 break;
24             }
25         }
26         return result;
27     }
28     
29     public void inOrderTraverse(TreeNode node, ArrayList<Integer> elems){
30         if(node == null){
31             return;
32         }
33         if(node.left != null){
34             inOrderTraverse(node.left, elems);
35         }
36         elems.add(node.val);
37         if(node.right != null){
38             inOrderTraverse(node.right, elems);
39         }
40         
41     }
42 }

2.判断一个tree是不是BST需要满足如下几点:

a.左子树的节点都小于当前node值

b.右子树的节点都大于当前node值

这里通过传递每个节点的上下界来判断该子节点是否符合要求

 1 public boolean isValidBST(TreeNode root) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         return isBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
 5     }
 6     
 7     public boolean isBSTHelper(TreeNode node, int low, int high){
 8         if(node == null){
 9             return true;
10         }
11         int value = node.val;
12         if(low < value && value < high &&
13             isBSTHelper(node.left, low, value) &&
14             isBSTHelper(node.right, value, high)){
15                 return true;
16             } else {
17                 return false;
18             }
19     }

 

 http://leetcode.com/2010/09/determine-if-binary-tree-is-binary.html

http://tech-wonderland.net/blog/leetcode-validate-binary-search-tree.html

你可能感兴趣的:(Binary search)