LeetCode -- Validate Binary Search Tree

来源:互联网 发布:气象数据下载 编辑:程序博客网 时间:2024/04/29 17:12
题目描述:


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.


就是判断一个二叉树是否为搜索二叉树。


搜索二叉树的定义为,左子树的每个节点都小于当前节点;右子树的每个节点都大于当前节点。


思路:中序遍历节点存入数组,再判断数组是否为递增(不包括相等)。


实现代码:


/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {    public bool IsValidBST(TreeNode root)     {        var result = new List<int>();    Travel(root, ref result);        for(var i = 0;i < result.Count - 1; i++){    if(result[i+1] <= result[i]){    return false;    }    }        return true;    }private void Travel(TreeNode node ,ref List<int> result){if(node == null){return;}Travel(node.left, ref result);result.Add(node.val);Travel(node.right, ref result);}}


1 0