LeetCode 11.30

107 阅读1分钟

LeetCode 141 环状链表

//如果是环状链表,一直往下遍历的次数一定会超过最大的结点数量。
var hasCycle = function(head) {
    let count = 1;
    if(head===null) return false;
    while(count<=10000){
        if(head.next!==null){
            head = head.next;
            count++;
        }
        else{
            return false;
        }
    }
    return true;
};
//快慢指针,fast每次都多走一步,如果有环一定会相遇。
var hasCycle = function(head) {
    let fast = head;
    let slow = head;
    if(fast==null||fast.next==null){
         return false;
    }
    fast = fast.next.next;
    slow = slow.next;   
    while(fast!==slow){
        if(fast==null||fast.next==null){
            return false;
        }
        fast = fast.next.next;
        slow = slow.next;
    }
    return true;
};
//利用set,需要注意的是指针是引用存储,可以根据结点地址判断结点是否已存在。
var hasCycle = function(head) {
    let set = new Set();
    if(head==null) return false;
    while(head.next!==null){
        if(set.has(head)){
            return true;
        }
        else{
            set.add(head);
            head = head.next;
        }
    }
    return false
};

LeetCode 104 二叉树最大深度

//深度优先搜索
var maxDepth = function(root) {
    if(root===null) return 0;
    return dfs(0,root);
};
let dfs = (num, head) =>{
    if(head.left===null){
        if(head.right===null){
            return 1+num;
        }
        return dfs(num+1, head.right);
    }
    else{
        if(head.right===null){
            return dfs(num+1, head.left);
        }
        return Math.max(dfs(num,head.left),dfs(num,head.right))+1;
    }
}

LeetCode 98 验证二叉搜索树

//左边的每一个结点都要比根节点小,所以哪怕是左子树的右子树,也要小于根节点的值。同理右子树,所以要保存当前状态的最值。
var isValidBST = function(root) {
    return funct(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
};
var funct = (root, small, big)=>{
    if(root===null) return true;
    if(root.val<=small||root.val>=big){
        return false;
    }
    return funct(root.left, small, root.val)&&funct(root.right, root.val, big);
}
//中序遍历
var isValidBST = function(root) {
    let arr = [];
    trace_back(arr,root);
    for(let i = 0;i<arr.length-1;i++){
        if(arr[i]>=arr[i+1]){
            return false;
        }
    }
    return true;
};
let trace_back = (arr, root)=>{
    if(root===null) return;
    trace_back(arr,root.left);
    arr.push(root.val);
    trace_back(arr, root.right);
}
//无递归的中序遍历
var isValidBST = function(root) {
    let standard = Number.MIN_SAFE_INTEGER;
    let stack = [];
    while(stack.length||root!==null){
        while(root!==null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        if(root.val<=standard){
            return false;
        }
        standard = root.val;
        root = root.right;
    }
    return true;
};