Leetcode 513 树左下角的值 DFS 与 BFS

  DFS 解法:

 public final int findBottomLeftValue(TreeNode root) {
        if (root == null) return 0;
        return find(root, 0).node.val;
    }

    private final NodeAndDepth find(TreeNode node, int depth) {
        if (node.left == null && node.right == null) return new NodeAndDepth(depth, node);
        NodeAndDepth child = null;
        int nextDept = depth + 1;
        if (node.left != null) child = find(node.left, nextDept);
        if (node.right != null) {
            NodeAndDepth right = find(node.right, nextDept);
            if (child == null) child = right;
            else child = child.depth >= right.depth ? child : right;
        }
        return child;
    }

    private class NodeAndDepth {
        int depth;
        TreeNode node;

        NodeAndDepth(int depth, TreeNode node) {
            this.depth = depth;
            this.node = node;
        }
    }

  BFS 解法:

    public final int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue0 = new LinkedList<TreeNode>();
        Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
        queue0.add(root);
        TreeNode re = null;
        while (!queue0.isEmpty() || !queue1.isEmpty()) {
            while (!queue0.isEmpty()) re = putChilds(queue0, queue1);
            while (!queue1.isEmpty()) re = putChilds(queue1, queue0);
        }
        return re==null?0:re.val;
    }

    private final TreeNode putChilds(Queue<TreeNode> queue0, Queue<TreeNode> queue1) {
        TreeNode re = queue0.peek();
        while (!queue0.isEmpty()) {
            TreeNode node = queue0.poll();
            if (node.left != null) queue1.add(node.left);
            if (node.right != null) queue1.add(node.right);
        }
        return re;
    }

  JS DFS:

var findBottomLeftValue = function (root) {
    if (!root) return 0;
    return find(root, 0).node.val;
};

var find = function (node, depth) {
    if (!node.left && !node.right) return new NodeAndDepth(node, depth);
    let re, nextDepth = depth + 1;
    if (node.left) re = find(node.left, nextDepth);
    if (node.right) {
        let right = find(node.right, nextDepth);
        if (!re) re = right;
        else re = re.depth >= right.depth ? re : right;
    }
    return re;
}

var NodeAndDepth = function (node, depth) {
    this.node = node;
    this.depth = depth;
}

  JS BFS:

var findBottomLeftValue = function (root) {
    if (!root) return 0;
    let queue = [root];
    let re = root;
    while (queue.length > 0) {
        re = queue[0];
        let len = queue.length;
        for (let i = 0; i < len; i++) {
            let node = queue.shift();
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
    }
    return re.val;
}

当你看清人们的真相,于是你知道了,你可以忍受孤独
原文地址:https://www.cnblogs.com/niuyourou/p/13908409.html