404. Sum of Left Leaves
404. Sum of Left Leaves Line 18: error: '.class' expected https://leetcode.com/problems/sum-of-left-leaves/discuss/88950/Java-iterative-and-recursive-solutions 1 \ 2 Return 0 , instead of 2 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 3 / \ 9 20 / \ / \ 1 2 5 7 Left leaf sum is 1 + 5 in this case /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // traverse by level // if a node has a left child and // 1. its. a leaf, add it to the sum // 2 not a leaf, add it to the queue // 3 the node has a right child // if its a leaf, do nothing // if has a child or chidren, add it to the queue class Solution { public int sumOfLeftLeaves(TreeNode root) { int sum = 0; Queue<TreeNode> queue = new LinkedList<>(); if(root == null) return 0; if(helper(root)) return 0; queue.offer(root); while(!queue.isEmpty()){ TreeNode cur = queue.poll(); if(cur.left != null){ if(helper(cur.left)) { sum += cur.left.val; }else { queue.offer(cur.left); } } if(cur.right != null && !helper(cur.right)){ queue.offer(cur.right); } } return sum; } // check if a node is a leaf private boolean helper(TreeNode node){ if(node.left == null && node.right == null){ return true; } return false; } } /////// others recursive way from leetcode https://leetcode.com/problems/sum-of-left-leaves/discuss/88950/Java-iterative-and-recursive-solutions Recursive method. For given node we check whether its left child is a leaf. If it is the case, we add its value to answer, otherwise recursively call method on left child. For right child we call method only if it has at least one nonnull child. public int sumOfLeftLeaves(TreeNode root) { if(root == null) return 0; int ans = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) ans += root.left.val; else ans += sumOfLeftLeaves(root.left); } ans += sumOfLeftLeaves(root.right); return ans; }
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
posted on 2018-08-09 16:51 猪猪🐷 阅读(90) 评论(0) 收藏 举报
浙公网安备 33010602011771号