404. Sum of Left Leaves

来源:互联网 发布:WiFi无法连接网络? 编辑:程序博客网 时间:2024/04/30 16:05

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

解法一:Language-Java Time-O(n) Spaca-O(logn) Run Time-9ms
注:n代表树的节点数
时间复杂度:T(n) = 2T(n/2) 解得O(n)
空间复杂度:递归了logn层,每层都有个res,得O(logn)

public class Solution {    public int sumOfLeftLeaves(TreeNode root) {        int res = 0;        //如果是一颗空树或者是一颗只有根节点的树        if(root == null || (root.left == null && root.right == null))        {            return res;        }        if(root.left != null)        {            //如果是左叶子节点            if(root.left.left == null && root.left.right == null)            {                res += root.left.val;            }else            {                res += sumOfLeftLeaves(root.left);            }        }        if(root.right != null)        {            if(root.right.left != null || root.right.right != null)            {                res += sumOfLeftLeaves(root.right);            }        }        return res;    }}
0 0