Skip to main content
🌟 Loving the project? Support our open-source journey with a
Star on GitHub
!
Algo
Tutorials
Interview Engine
System Preparation
Verification Roadmap
Core Matrix Questions
Real-World Implementation
Contribution Tracker
Evaluation Pools
Code Challenges
Practice Arena
Concept Quizzes
Compiled Solutions
Community Hub
Telemetry & Systems
Contributors Wall
Global Leaderboard
Milestones & Badges
Infrastructure Patrons
Ecosystem Labs
Code Playground
Algorithm Visualizer
Recursion Visualizer
Success Stories
Public Discussions
Extended Assets
FAQ
Blogs
English
English
हिन्दी
Search
Sign Up
Back to Challenges
Sum of All Nodes
Easy
15 min
problem
solution
Sum of All Nodes
Given the root of a binary tree, return the **sum of all node values** in the tree.
Examples
Input:
root = [1,2,3,4,5]
Output:
15
1+2+3+4+5 = 15.
Input:
root = [-1,2,-3]
Output:
-2
-1+2+(-3) = -2.
Constraints
•
Number of nodes in [0, 10^4]
•
-1000 <= Node.val <= 1000
Complexity Analysis
Time
O(n)
Space
O(h)
Show Hint
Test Cases
#1 Positive values
Input:
[1,2,3,4,5]
Expected:
15
#2 Mixed signs
Input:
[-1,2,-3]
Expected:
-2
#3 Empty tree
Input:
[]
Expected:
0
#4 Single node
Input:
[7]
Expected:
7
JavaScript
Run Code
class TreeNode { constructor(val, left = null, right = null) { this.val = val; this.left = left; this.right = right; } } function buildTree(arr) { if (!arr || arr.length === 0) return null; const root = new TreeNode(arr[0]); const q = [root]; let i = 1; while (q.length && i < arr.length) { const n = q.shift(); if (arr[i] != null) { n.left = new TreeNode(arr[i]); q.push(n.left); } i++; if (i < arr.length && arr[i] != null) { n.right = new TreeNode(arr[i]); q.push(n.right); } i++; } return root; } /** * @param {TreeNode} root * @return {number} */ function sumOfAllNodes(root) { // Your code here } const root = buildTree([1,2,3,4,5]); console.log(sumOfAllNodes(root)); // Expected: 15
Output
Click "Run Code" to see output here...