美文网首页
111. Minimum Depth of Binary Tre

111. Minimum Depth of Binary Tre

作者: exialym | 来源:发表于2016-09-21 22:47 被阅读6次

    Given a binary tree, find its minimum depth.

    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
    这道题用递归会非常好做,但是会遍历到每个叶子节点,这是不必要的,当一个节点的深度已经大于之前的某个子节点的深度时候,这个节点的子节点就不必遍历了。

    var minDepth = function(root) {
        if(root === null) return 0;
        var left = minDepth(root.left);
        var right = minDepth(root.right);
        return (left === 0 || right === 0) ? left + right + 1: Math.min(left,right) + 1;
    };
    

    非递归

    var minDepth = function(root) {
        if (!root)
            return 0;
        var depth = 99999;
        root.val = 1;
        var stack = [root];
        while (stack.length!==0) {
            var node = stack.pop();
            
            if ((node.val+1)<depth) {
                if (node.left) {
                    node.left.val = node.val+1;
                    stack.push(node.left);
                }
                if (node.right) {
                    node.right.val = node.val+1;
                    stack.push(node.right);
                }   
            }
            if (!node.left&&!node.right) {
                if (node.val<depth) {
                    depth = node.val;
                }
            }
        }
        return depth;
    };
    

    相关文章

      网友评论

          本文标题:111. Minimum Depth of Binary Tre

          本文链接:https://www.haomeiwen.com/subject/fkmlettx.html