题解 | #判断是不是二叉搜索树#

判断是不是二叉搜索树

http://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b

  • 用遍历的思维,采用中序遍历必须为递增才是二叉搜索树,结合外部变量。
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

class Solution {
    boolean isBST = true; //外部变量
    TreeNode pre = null;
    public boolean isValidBST (TreeNode root) {
        // write code here
        inOrder(root);
        return isBST;
    }
    
    // 通过遍历+外部变量实现
    private void inOrder(TreeNode root){
        if(root == null)
            return;
        inOrder(root.left);
        /* 中序遍历位置 */
        if(pre != null && pre.val >= root.val){ //不是递增有序
            isBST = false;
            return;
        }
        pre = root; //当前节点中序遍历结束,变成前一个遍历的节点
        inOrder(root.right);
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务