Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

This is to test your knowledge on BST and its traversal. 

Flatting BST into an array using in-order, and check that array. It is that simple:

class Solution {
public:
    void serial(TreeNode *root, vector<int> &vec)
    {
        if (!root) return;

        if (root->left)        serial(root->left, vec);
        vec.push_back(root->val);
        if (root->right)    serial(root->right, vec);
    }
    bool isValidBST(TreeNode *root) {
        if (!root) return true;

        vector<int> arr;
        serial(root, arr);

        for (int i = 0; i < arr.size() - 1; i ++)
        {
            if (arr[i + 1] <= arr[i]) return false;
        }
        return true;
    }
};
posted on 2014-07-17 15:44  Tonix  阅读(143)  评论(0编辑  收藏  举报