标签:
题目解析:(链接)
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
解题思路:
先用中序遍历将bst的所有节点值保存起来,然后验证:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isValidBST(TreeNode* root) { 13 if (root == nullptr) { 14 return true; 15 } 16 17 inorder(root); 18 19 for (int i = 0; i < cache.size() - 1; ++i) { 20 if (cache[i] >= cache[i+1]) { 21 return false; 22 } 23 } 24 25 return true; 26 } 27 28 private: 29 vector<int> cache; 30 void inorder(TreeNode *root) { 31 if (!root) return; 32 inorder(root->left); 33 cache.push_back(root->val); 34 inorder(root->right); 35 } 36 37 };
错误解法:
该解法只是比较了根节点和他的左节点和右节点,没有递归比较和整个左子树和右子树,根节点应该大于所有左子树节点,小于所有右子树节点。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isValidBST(TreeNode* root) { 13 if (root == nullptr) { 14 return true; 15 } 16 17 if (root->left != nullptr && root->left->val >= root->val) { 18 return false; 19 } 20 21 if (root->right != nullptr && root->right->val <= root->val) { 22 return false; 23 } 24 25 return isValidBST(root->left) && isValidBST(root->right); 26 } 27 28 };
[LeetCode]Validate Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/skycore/p/5025411.html