【LeetCode & 剑指offer刷题】树题13:Validate Binary Search Tree
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Validate Binary Search Tree
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.
Example 1:
Input:
2
/ \
1 3
Output:
true
Example 2:
5
/ \
1 4
/ \
3 6
Output:
false
Explanation:
The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
C++
/**
* 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
:
bool
isValidBST
(
TreeNode
*
root
)
{
if
(
root
==
NULL
)
return
true
;
stack
<
TreeNode
*>
s
;
TreeNode
*
p
=
root
;
TreeNode
*
pre
=
NULL
;
while
(!
s
.
empty
()
||
p
)
{
if
(
p
)
{
s
.push(p);
p
=
p
->
left
;
}
else
{
p
=
s
.
top
();
if(pre != NULL && p->val <= pre->val) return false; //看是否为升序
pre = p; //保存已经访问的结点
s
.
pop
();
p
=
p
->
right
;
}
}
return
true
;
}
};
//参考:
while
(
p
!=
nullptr
||
!
s
.
empty
())
{
if
(
p
!=
nullptr
)
//
当左结点不为空时
{
s
.
push
(
p
);
//
入栈
p
=
p
->
left
;
//
指向下一个
左结点
}
else
//
当左结点为空时
{
p
=
s
.
top
();
path
.
push_back
(
p
->
val
);
//
访问栈顶元素(父结点)
s
.
pop
();
//
出栈
p
=
p
->
right
;
//
指向
右结点
}
}