Leetcode 404 左叶子之和 BFS与DFS

  题目简单,练习一下 BFS 与 DFS。

  BFS:

    private final boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;
    }

    public final int sumOfLeftLeavesBFS(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int res = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                if (isLeaf(node.left)) res += node.left.val;
                else queue.offer(node.left);
            }
            if (node.right != null && !isLeaf(node.right)) queue.offer(node.right);
        }
        return res;
    }

  DFS:

    public final int sumOfLeftLeaves(TreeNode root) {
        return sumOfLeftLeavesDFS(root);
    }

    public final int sumOfLeftLeavesDFS(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        if (root.left != null) {
            if (isLeaf(root.left)) res += root.left.val;
            else res += sumOfLeftLeavesDFS(root.left);
        }
        if (root.right != null && !isLeaf(root.right)) res += sumOfLeftLeavesDFS(root.right);
        return res;
    }

    private final boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;
    }

  JS BFS:

var isLeaf = function (node) {
    return node.left == null && node.right == null;
}


var sumOfLeftLeaves = function (root) {
    if (root == null) return 0;
    let queue = [];
    queue.push(root);
    let res = 0;
    while (queue.length > 0) {
        let node = queue.shift();
        if (node.left != null) {
            if (isLeaf(node.left)) res += node.left.val;
            else queue.push(node.left);
        }
        if (node.right != null && !isLeaf(node.right)) queue.push(node.right);
    }
    return res;
}

  JS DFS:

var sumOfLeftLeaves = function (root) {
    if (root == null) return 0;
    return dfs(root);
};

var dfs = function (node) {
    let res = 0;
    if (node.left != null) {
        if (isLeaf(node.left)) res += node.left.val;
        else res += dfs(node.left);
    }
    if (node.right != null && !isLeaf(node.right)) res += dfs(node.right);
    return res;
}

var isLeaf = function (node) {
    return node.left == null && node.right == null;
}

 

posted @ 2020-09-25 00:54  牛有肉  阅读(107)  评论(0编辑  收藏  举报