【LeetCode】Sum of Left Leaves 解题报告

来源:互联网 发布:先锋网络电视vip 编辑:程序博客网 时间:2024/05/16 16:03

【LeetCode】Sum of Left Leaves 解题报告

标签(空格分隔): LeetCode


[LeetCode]

https://leetcode.com/problems/sum-of-left-leaves/

  • Difficulty: Easy

Question

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

Example:    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

Ways

这个方法很直白很简单,用递归判断是不是左叶子,然后求和即可。我的第一次A过的代码是这样的。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int sum=0;    public int sumOfLeftLeaves(TreeNode root) {        if(root==null){            return 0;        }        if(root.left!=null){            if(root.left.left==null && root.left.right==null){//根的左边节点是叶子                sum += root.left.val;//加上左叶子的值            }            sumOfLeftLeaves(root.left);//循环左叶子        }        if(root.right!=null){            sumOfLeftLeaves(root.right);//循环右叶子        }        return sum;    }}

AC:8 ms

看了高票解答之后,感觉自己还可以精简下代码。如下。

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

AC:9 ms

Date

2017 年 1 月 7 日

0 0
原创粉丝点击