Leetcode - Sum of Left Leaves

My code:
recursion

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int ret = 0;
        if (root.left != null) {
            if (root.left.left == null && root.left.right == null) {
                ret += root.left.val;
            }
            else {
                ret += sumOfLeftLeaves(root.left);
            }
        }
        if (root.right != null) {
            ret += sumOfLeftLeaves(root.right);
        }
        
        return ret;
    }
}

iteration:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        int ret = 0;
        while (!q.isEmpty()) {
            TreeNode curr = q.poll();
            if (curr.left != null) {
                if (curr.left.left == null && curr.left.right == null) {
                    ret += curr.left.val;
                }
                else {
                    q.offer(curr.left);
                }
            }
            if (curr.right != null) {
                q.offer(curr.right);
            }
        }
        
        return ret;
    }
}

reference:
https://discuss.leetcode.com/topic/60403/java-iterative-and-recursive-solutions/2

竟然没写出来。哎,早点休息了。

Anyway, Good luck, Richardo! — 10/11/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/22fc5c0970ea
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞