给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例
输入:
2
/ \
1 3
输出: true
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
解法
首先中序遍历二叉树,将其 val 添加至列表中
然后遍历列表,如果不是升序则二叉树无效
public bool IsValidBST(TreeNode root)
{
if (root == null) return true;
IList<int> res = new List<int>();
AddValues(res, root);
for (int i = 1; i < res.Count; i++)
{
if (res[i - 1] >= res[i]) return false;
}
return true;
}
public void AddValues(IList<int> res, TreeNode root)
{
if (root.left != null)
{
AddValues(res, root.left);//左节点
}
res.Add(root.val);//当前节点
if (root.right != null)
{
AddValues(res, root.right);//右节点
}
}