LeetCode 98. Validate Binary Search Tree 题解

    xiaoxiao2021-03-25  55

    题目链接:https://leetcode.com/problems/validate-binary-search-tree/?tab=Description

    思路:二叉搜索树的中序遍历应该是递增的序列,可以通过判断中序遍历的序列是否是严格增长的,来判断二叉树是否是二叉搜索树。

    Java代码如下:

    public class Solution { private List<TreeNode> nodeList = new LinkedList<TreeNode>(); // 中序遍历 public void midPrint(TreeNode root){ if(root == null){ return; } midPrint(root.left); TreeNode node = root; nodeList.add(node); midPrint(root.right); } public boolean isValidBST(TreeNode root) { midPrint(root); if(nodeList == null || nodeList.size()==0){ return true; } else { int num = nodeList.get(0).val; // 中序遍历是否是递增的,且数据不能重复 for(int i=1; i<nodeList.size(); i++){ if(nodeList.get(i).val <= num){ return false; } else{ num = nodeList.get(i).val; } } } return true; } }

    转载请注明原文地址: https://ju.6miu.com/read-37408.html

    最新回复(0)