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

转载于:https://www.cnblogs.com/feiling/p/3260967.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值