标签:style blog color os io ar for div 问题
给定一个BST的根节点, 试判断此BST是否为符合规则的BST?
规则: 对于一个BST的节点,
算法思路: 对于给定的根节点N, 先找到它左子节点L的最底层的右子节点MR, 比较MR和N的值, 如果 MR >= N, 则返回false; 再找到N右子节点R的最底层的左子结点ML, 比较ML和N的值, 如果 ML <= N, 则返回false; 最后, 递归遍历左右节点, 将两者的返回值取逻辑与后返回.
代码:
1 /**
2 * Definition for binary tree
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 (NULL == root) return true;
14 TreeNode *left = root->left, *right = root->right;
15 if (left) {
16 TreeNode *pre = left;
17 while (pre->right) pre = pre->right;
18 if (pre->val >= root->val) return false;
19 }
20 if (right) {
21 TreeNode *post = right;
22 while (post->left) post = post->left;
23 if (post->val <= root->val) return false;
24 }
25 return (isValidBST(left) && isValidBST(right));
26 }
27 };
标签:style blog color os io ar for div 问题
原文地址:http://www.cnblogs.com/lancelod/p/3962568.html