leetcode刷题日记之验证二叉搜索树

题目:

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

一个二叉搜索树有如下定义:

左子树只包含小于当前节点的数。
右子树只包含大于当前节点的数。
所有子树自身必须也是二叉搜索树。

示例 1:

2
/ \
1 3

二叉树[2,1,3], 返回 true.

示例 2:

1
/ \
2 3

二叉树 [1,2,3], 返回 false.

解题思路:二叉搜索树中序遍历之后是一个有序序列。所以借用此性质,先中序遍历该二叉搜索树,然后判断该序列是否有序即可。

c++解法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        vector<int> v;
        inOrder(root, v);
        for (int i = 1; i < v.size(); i ++){
            if (v[i - 1] >= v[i]) return false;
        }
        return true;
    }
private:
    void inOrder(TreeNode* root, vector<int> &v){//中序遍历
        if (root != NULL){
            inOrder(root->left, v);
            v.push_back(root->val);
            inOrder(root->right, v);
        }
    }
};

python解法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inOrder(self, root, arr):
        if root:
            self.inOrder(root.left, arr)
            arr += [root.val]
            self.inOrder(root.right, arr)
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        arr = []
        self.inOrder(root, arr)
        for i in range(1, len(arr)):
            if arr[i-1] >= arr[i]:
                return False
        return True

猜你喜欢

转载自blog.csdn.net/qq_35327651/article/details/79843297
今日推荐