[Leetcode] 98. 验证二叉搜索树

2019-02-19 09:43:31 +08:00
 Acceml

题目

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5,但是其右子节点值为 4。

题解

这道题目主要是利用二叉搜索树的一个性质: 二叉搜索树的中序遍历结果是一个升序的序列。 那么问题转变成:中序遍历 + 验证是不是升序.

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

1984 次点击
所在节点    C
2 条回复
ahonn
2019-02-19 10:03:02 +08:00
递归就完了
aijam
2019-02-19 10:05:31 +08:00
简单递归题需要什么中序

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/536385

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX