中等题-二叉搜索树的性质
利用二叉搜索树中序遍历一定是升序的

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
}
}
//前中后序遍历的模版
public static void preOrder(TreeNode root,List<TreeNode> list){
//前序遍历
if(root==null)return;
list.add(root);
preOrder(root.left,list);
preOrder(root.right,list);
}
public static void inOrder(TreeNode root,List<TreeNode> list){
//中序遍历
if(root==null)return;
inOrder(root.left,list);
list.add(root);
inOrder(root.right,list);
}
public static void postOrder(TreeNode root,List<TreeNode> list){
//后序遍历
if(root==null)return;
postOrder(root.left,list);
postOrder(root.right,list);
list.add(root);
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
List<TreeNode> list=new ArrayList<>();
inOrder(root,list);
long pre=Long.MIN_VALUE;
for(TreeNode val:list){
if(val.val<=pre)return false;
pre=val.val;
}
return true;
}
public void inOrder(TreeNode root,List<TreeNode> list){
//中序遍历
if(root==null)return;
inOrder(root.left,list);
list.add(root);
inOrder(root.right,list);
}
}

浙公网安备 33010602011771号