LeetCode题解: Validate Binary Search Tree
2013-11-13 12:33
387 查看
Validate Binary Search Tree
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.
思路:
仍然是树的深度优先搜索。这里要注意的是,不能仅仅和父结点的值比较,还必须和上面所有的结点进行比较。
题解:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<pair<int, char>> history; bool isValidBST(TreeNode *node) { if (node == nullptr) return true; // check if I am ok with all the parents for(auto& h : history) if (h.second == 'R') { // i am at the right subtree if (node->val <= h.first) return false; } else { // i am at the left subtree if (node->val >= h.first) return false; } bool leftok = true; history.push_back(make_pair(node->val, 'L')); leftok = isValidBST(node->left); bool rightok = true; history.back().second = 'R'; rightok = isValidBST(node->right); history.pop_back(); return leftok && rightok; } };
相关文章推荐
- LeetCode题解——Validate Binary Search Tree
- [LeetCode 题解]: Validate Binary Search Tree
- [LeetCode]题解(python):098- Validate Binary Search Tree
- LeetCode题解-98-Validate Binary Search Tree
- 【题解】【BST】【Leetcode】Validate Binary Search Tree
- leetcode 题解 98. Validate Binary Search Tree
- LeetCode题解:Validate Binary Search Tree
- Leetcode 98.Validate Binary Search Tree
- leetcode - Validate Binary Search Tree
- LeetCode Validate Binary Search Tree
- [LeetCode 98] Validate Binary Search Tree
- Leetcode[98]-Validate Binary Search Tree
- LeetCode: Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [Leetcode 98] Validate Binary Search Tree
- LeetCode 54 Validate Binary Search Tree
- 098 Validate Binary Search Tree [Leetcode]
- 【LeetCode】Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- Leetcode优化:Validate Binary Search Tree