Binary Tree Level Sum

题目:

Given a binary tree and an integer which is the depth of the target level.

Calculate the sum of the nodes in the target level.

分析:

题目本身不难,但是做的时候好像超过15min了,最近手有点生

解法:(bfs)

public class Solution {
    /**
     * @param root the root of the binary tree
     * @param level the depth of the target level
     * @return an integer
     */
    public int levelSum(TreeNode root, int level) {
        // Write your code
        int res = 0;
        if (root == null) {
            return res;
        }

        Queue<TreeNode> myQueue = new LinkedList<TreeNode>();
        myQueue.offer(root);

        int levelCount = 0;
        int size = 0;

        while(!myQueue.isEmpty() ) {
            size = myQueue.size();
            levelCount += 1;

            if (levelCount == level) {
                break;
            }

            for (int i = 0; i < size; i++) {
                TreeNode temp = myQueue.poll();
                if (temp.left != null) {
                    myQueue.offer(temp.left);
                }
                if (temp.right != null) {
                    myQueue.offer(temp.right);
                }
            }
        }

        if (!myQueue.isEmpty() ) {
            for (int i = 0; i < size; i++) {
                TreeNode temp = myQueue.poll();
                res += temp.val;
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""