Leetcode 404) Sum of Left Leaves

image

내 답안

/**
 * 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 {
    public int sumOfLeftLeaves(TreeNode root) {
        Queue<TreeNode>  thisLevel= new LinkedList<>();
        thisLevel.add(root);
        int sum=0;
        while(!thisLevel.isEmpty()){
            int size= thisLevel.size();
            for(int i=0;i<size;i++){
                TreeNode cur= thisLevel.poll();
                if(cur!=null){
                    thisLevel.add(cur.left);
                    if(cur.left!=null){
                        if(cur.left.left==null && cur.left.right==null){
                            sum+=cur.left.val;
                        }
                    }
                    thisLevel.add(cur.right);
                }
            }
        }
        return sum;
    }
}

다른 답안

/**
 * 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 res = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        traverse(root);
        return res;
    }
    
    public void traverse(TreeNode node) {
        if(node == null) return;
        if(node.left!=null && node.left.left == null && node.left.right ==null ) res+=node.left.val;
        traverse(node.left);
        traverse(node.right);
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2