LeetCode(98) Validate Binary Search Tree解题报告

来源:互联网 发布:培训学校课时软件 编辑:程序博客网 时间:2024/06/06 03:18

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.

解题思路:

中序遍历获取结点序列,如果是一个BST,那么序列一定是从小到大排好序的……

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {     public boolean isValidBST(TreeNode root) {       List<Integer> res = inorderTraversal(root);       for(int i = 1; i < res.size(); i++){           if(res.get(i) <= res.get(i-1))               return false;       }       return true;    }    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> res = new ArrayList<Integer>();        if(root != null){            res.addAll(inorderTraversal(root.left));            res.add(root.val);            res.addAll(inorderTraversal(root.right));        }        return res;    }}

下面附上网上的一种高效解法,也是中序遍历,不过是直接比较,省下了存储结点值得空间,也省下了检测顺序的时间,从LeetCode的提交结果分布来看,这种应该是最优的解法之一了。

/** * 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 = null;     public boolean isValidBST(TreeNode root) {        if(root != null){            if(!isValidBST(root.left))                return false;            if(prev != null && prev.val >= root.val)                return false;            prev = root;            return isValidBST(root.right);              }        return true;    }   }
0 0
原创粉丝点击