LeetCode 98. Validate Binary Search Tree
来源:互联网 发布:植村秀淘宝旗舰店 编辑:程序博客网 时间:2024/06/02 21:05
题目
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.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
思路
开始觉得这题目应该挺简单,直接递归左右子树,后来发现这个思路有很大的问题,只是保证左右子节点满足条件,而无法保证左子树的所有元素小于根节点(或者右子树所有元素大于根节点)。
这样的话可以想到用中序遍历来遍历所有节点,用递归实现中序遍历。
先遍历左子树,左子树不满足条件则返回false;
再查看根节点,如果根节点的值小于等于前面的部分则返回false;
最后遍历右子树。
二叉搜索树的中序遍历是一个递增的序列,所以这里用pre来表示中序遍历时当前结点前面的值,保证后面的值都比前面要小。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* pre=NULL; bool isValidBST(TreeNode* root) { if(root==NULL) return true; return inOrder(root); } bool inOrder(TreeNode* root) { if(root==NULL) return true; if(!inOrder(root->left)) return false; //遍历左子树 if(pre != NULL && root->val <= pre->val) //查看根节点 return false; pre = root; return inOrder(root->right); //遍历右子树 }};
- LeetCode 98. Validate Binary Search Tree
- [LeetCode]98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree
- LeetCode --- 98. Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree @python
- Leetcode 98. Validate Binary Search Tree
- [LeetCode]98. Validate Binary Search Tree
- leetcode 98. Validate Binary Search Tree
- *LeetCode 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree LeetCode
- LeetCode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- LeetCode *** 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree-leetcode-java
- [leetcode] 98. Validate Binary Search Tree
- LeetCode - 98. Validate Binary Search Tree
- 安卓仿手机网易新闻app项目开发系列之(四)数据分离与填充界面 下
- 【LeetCode】629. K Inverse Pairs Array
- 快速将多个excel表合并成一个excel表
- 第二章 使用Bootstrap的准备-tab标签小案例 笔记3
- spring 疑问汇总
- LeetCode 98. Validate Binary Search Tree
- PHP扩展及PHP7.0安装
- 活动界面重复返回
- 在ubuntu下编译多个C++文件
- 学习互联网架构第八课(单例和多线程)
- 多个Fragment界面重叠和拍照闪退问题
- NPOI的文件流
- spring中的Cglib字节码增强实现AOP
- css揭秘读书笔记(一)