2016年12月3日星期六

leetcode做题记录 —— sum-of-left-leaves

sum-of-left-leaves 
Find the sum of all left leaves in a given binary tree.
Example:
1.         3    
2.        /  \   
3.       9    20
4.           /  \   
5.           15   7 
There are two left leaves in the binary tree, with values 9 and 15 
respectively. Return 24.
给定一个二叉树,求所有左叶子节点的和。

解法

这题比较简单,做个递归把左叶子节点的的值加起来就可以了。
1.//Javascript
2./**
3. * Definition for a binary tree node.
4. * function TreeNode(val) {
5. *     this.val = val;
6. *     this.left = this.right = null;
7. * }
8. */
9./**
10. * @param {TreeNode} root
11. * @return {number}
12. */
13.var sumOfLeftLeaves = function(root) {
14.    let sum = 0;
15.    if(root === null)
16.    {
17.        return 0;
18.    }
19.    if( root.left && root.left.val && !root.left.left && !root.left.right )
20.    {
21.        return root.left.val + sumOfLeftLeaves(root.right);
22.    }
23.    return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
24.};
End

1 条评论 :

tabbieueno 说...

We may permanently block any person who abuses these situations. As of June 15, 2022, feedback on DenverPost.com are powered by Viafoura, and you might must log in once more to start commenting. If you need assistance or are having issues with your commenting account, please email us at We can’t say for certain whether or not Spin 1xbet korea Casino will tick all the boxes for you. Perhaps the one way to actually know for certain is signal up|to enroll}, claim its welcome bonus as much as} C$1,000 and 100FS, and find out.

发表评论