码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 098 Validate Binary Search Tree

时间:2015-05-21 22:32:43      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

本题方法多多,可以采用DFS,当然最简答的方法是采用之前的中序遍历Java for LeetCode 094 Binary Tree Inorder Traversal检查得到的List是否有序即可。

    public boolean isValidBST(TreeNode root) {

        List<Integer> list=inorderTraversal(root);
        if(list.size()==0)
            return true;
        int temp=list.get(0);
        for(int i=1;i<list.size();i++){
        	if(temp>=list.get(i))
        		return false;
        	temp=list.get(i);
        }
        return true;
    }
    public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();
    if(root==null)
        return list;
    if (root.left != null)
        list.addAll(inorderTraversal(root.left));
    list.add(root.val);
    if (root.right != null)
        list.addAll(inorderTraversal(root.right));
    return list;
    }

 

JAVA实现如下:

 

Java for LeetCode 098 Validate Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4520825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!