-
404. Sum of Left LeavesAlgorithm/java tip 2021. 3. 6. 22:10
leetcode.com/problems/sum-of-left-leaves/
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int sum = 0; public int sumOfLeftLeaves(TreeNode root) { if(root != null) traverse(root); return sum; } public boolean traverse(TreeNode root) { if(root.left != null) { boolean isLeaf = traverse(root.left); if(isLeaf) sum += root.left.val; } if(root.right != null) { traverse(root.right); } return root.left == null && root.right == null; } }
'Algorithm > java tip' 카테고리의 다른 글
589. N-ary Tree Preorder Traversal (0) 2021.03.13 78. Subsets (0) 2021.03.07 22. Generate Parentheses (0) 2021.03.06 559. Maximum Depth of N-ary Tree (0) 2021.03.06 [programmers] 가장 먼 노드 (0) 2021.03.06