LeetCode404. Sum of Left Leaves

题目

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

答案1

BFS

public int sumOfLeftLeaves(TreeNode root) {
    if (root == null || (root.left == null && root.right == null)) return 0;
    int result = 0;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        if (root.left != null && root.left.left == null && root.left.right == null) result += root.left.val;
        if (root.left != null) queue.offer(root.left);
        if (root.right != null) queue.offer(root.right);
    }
    return result;
}

答案2

DFS

public int sumOfLeftLeaves(TreeNode root) {
    if (root == null) return 0;
    int result = 0;
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    while (!stack.empty()) {
        root = stack.pop();
        if (root.right != null && (root.right.left != null || root.right.right != null)) stack.push(root.right);
        if (root.left != null) {
            if (root.left.left == null && root.left.right == null) result += root.left.val;
            else stack.push(root.left);
        }
    }
    return result;
}

答案3

递归

public int sumOfLeftLeaves(TreeNode root) {
    if (root == null) return 0;
    int result = 0;
    if (root.left != null) {
        if (root.left.left == null && root.left.right == null) result += root.left.val;
        else result += sumOfLeftLeaves(root.left);
    }
    result += sumOfLeftLeaves(root.right);
    return result;
}

猜你喜欢

转载自blog.csdn.net/wayne566/article/details/79457507