Leetcode-标签为Tree 404. Sum of Left Leaves

来源:互联网 发布:安卓6.0优化教程 编辑:程序博客网 时间:2024/06/08 12:04

原题

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.

代码实现

    public class LeftLeafSum    {        public int SumOfLeftLeaves(TreeNode root)        {            if (root == null)                return 0;            int sum=0;            if (root.left!=null && isLeaf(root.left))//左叶子                sum += root.left.val;            sum += SumOfLeftLeaves(root.left);            sum += SumOfLeftLeaves(root.right);            return sum;        }        private bool isLeaf(TreeNode node)        {            return node.left == null && node.right == null;        }    }
2 0
原创粉丝点击