[LeetCode]404. Sum of Left Leaves

来源:互联网 发布:网络开发客户的方法 编辑:程序博客网 时间:2024/06/05 01:52

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.
分析:求二叉树左叶子节点的数值之和

解题思路:层序遍历,当遍历到的节点的左子树存在,且该左子树为叶子结点。将它与sum累加求和。

public int sumOfLeftLeaves(TreeNode root) {        Queue<TreeNode> queue = new LinkedList<TreeNode>();        int sum = 0;        if(root==null)return 0;        queue.offer(root);        while(!queue.isEmpty()){            TreeNode node = queue.poll();            if(node.left!=null&&node.left.left==null&&node.left.right==null){                sum+=node.left.val;            }            if(node.left!=null)queue.offer(node.left);            if(node.right!=null)queue.offer(node.right);        }        return sum;    }
原创粉丝点击