码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode98 Validate Binary Search Tree

时间:2016-10-27 00:47:44      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:查找树   strong   等价   turn   判断   代码   中序遍历   help   root   

Given a binary tree, determine if it is a valid binary search tree (BST). (Medium)

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:

    2
   /   1   3

Binary tree [2,1,3], return true.

 

Example 2:

    1
   /   2   3

Binary tree [1,2,3], return false.

 

分析:

是否是二叉查找树和中序遍历是否以此递增是等价的,所以可以先做中序遍历,然后将结果数组做判断,注意判断空树。

代码:

 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 private:
12     vector<int> result;
13     void helper(TreeNode* root) {
14         if (root == nullptr) {
15             return;
16         }
17         helper(root -> left);
18         result.push_back(root -> val);
19         helper(root -> right);
20     }
21 public:
22     bool isValidBST(TreeNode* root) {
23          helper(root);
24          if (result.size() == 0) {
25              return true;;
26          }
27          for (int i = 0; i < result.size() - 1; ++i) {
28              if (result[i] >= result[i + 1])  {
29                  return false;
30              }
31          }
32          return true;
33     }
34 };

 

LeetCode98 Validate Binary Search Tree

标签:查找树   strong   等价   turn   判断   代码   中序遍历   help   root   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6002240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!