天天看點

leetcode刷題_OJ 98

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.

Example 1:

Input:

    2

   / \

  1   3

Output: true

Example 2:

    5

   / \

  1   4

     / \

    3   6

Output: false

Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.

題目的意思:給一個二叉樹,要求左子樹比根節點小,右子樹比根節點大,當樹内所有節點都滿足上述要求時,該二叉樹為有效的二分搜尋樹。

解題思路:看了很多很多大佬都是用的遞歸,這樣不用開辟新的空間,并且就樹而言也沒有什麼重複的計算。可是我一開始最直接的思路就是:給樹來一個中序周遊,這樣我們就能得到如題目中的序列。再對序列進行周遊。一旦出現前者比後者大的情況即可傳回false。

/**
 * 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) {
        if(root == NULL) return true;
        InOrder(root);
        for(int i=0;i<v.size()-1;i++){
        	if(v[i+1] <= v[i]) 
        		return false;
        }
        return true;
    }

    void InOrder(TreeNode* root){
    	if(root->left != NULL) InOrder(root->left);
    	v.push_back(root->val);
    	if(root->right != NULL) InOrder(root->right);
    }

private:
	vector<int> v;
};