美文网首页计算机Leetcode, again
Leetcode - Sum of Left Leaves

Leetcode - Sum of Left Leaves

作者: Richardo92 | 来源:发表于2016-10-12 14:41 被阅读20次

    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

    相关文章

      网友评论

        本文标题:Leetcode - Sum of Left Leaves

        本文链接:https://www.haomeiwen.com/subject/ngsiyttx.html