Java solution with Stack


  • 8
    Y
        public int sumOfLeftLeaves(TreeNode root) {
            int res = 0;
    
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                if (node != null) {
                    if (node.left != null && node.left.left == null && node.left.right == null)
                        res += node.left.val;
                    stack.push(node.left);
                    stack.push(node.right);
                }
            }
    
            return res;
        }
    

  • 1
    Y

    We can also use queue.

        public int sumOfLeftLeaves(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            int res = 0;
            TreeNode node = root;
            queue.offer(node);
            while(queue.size() != 0) {
                TreeNode head = queue.poll();
                if (head!= null) {
                    if ( head.left != null && head.left.left == null && head.left.right == null) {
                        res += head.left.val;
                    }
                    queue.offer(head.left);
                    queue.offer(head.right);
                }
            }
            
            return res;
        }
    

  • 0
    A

    Both solutions above are excellent. Thank you.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.