leetcode—98. 验证二叉搜索树

也不是我做出来的,,

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        res=[]
        def helper(root):
            if not root:
                return True
            helper(root.left)
            res.append(root.val)
            helper(root.right)
        helper(root)
        return res==sorted(res) and len(set(res))==len(res)
执行用时 :36 ms, 在所有 python 提交中击败了85.49%的用户
内存消耗 :17.7 MB, 在所有 python 提交中击败了5.07%的用户
 
——2019.11.7

 
自己写了一遍,用中序遍历的列表顺序进行判断的,不是很好的样子。
public boolean isValidBST(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        inOrder(root,list);
        int[] a = list.stream().mapToInt(Integer::valueOf).toArray();
        int[] b = Arrays.copyOf(a,a.length);
        Arrays.sort(a);
        if(a.length>1) {
            for (int i = 1; i < a.length; i++) {
                if (a[i] == a[i - 1]) {
                    return false;
                }
            }
        }
        return Arrays.equals(a, b);
    }
    //中序遍历
    private void inOrder(TreeNode node,ArrayList<Integer> list){
        if(node == null){
            return;
        }
        inOrder(node.left,list);
        list.add(node.val);
        inOrder(node.right,list);
    }

 

 ——2020.7.1

 
posted @ 2019-11-07 10:54  欣姐姐  阅读(139)  评论(0编辑  收藏  举报