मुख्य कंटेंट तक स्किप करें
🌟 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
Visualizers
Algorithm Visualizer
Big-O Runtime Benchmark Playground
Time Complexity Visualizer
Backtracking & Grid Solver
Bitwise Operations
N-Queens Visualizer
Largest Rectangle
Maximal Rectangle
Max Building Height
Community & Ecosystem
Telemetry & Systems
Contributors Wall
Global Leaderboard
Milestones & Badges
Infrastructure Patrons
Ecosystem Labs
Code Playground
Success Stories
Public Discussions
Extended Assets
Favorites
FAQ
Blog
Algorithm Digest
हिन्दी
English
हिन्दी
खोज करें
Back to Challenges
Sum of All Nodes
Mark as Solved ✅
Easy
15 min
Problem
Visualize ✨
Solution
Pseudocode
Sum of All Nodes
Try in Tree Sandbox →
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)
Complexity Deep Dive
Time:
O(n)
Good
·
Space:
O(h)
Expand
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
Python
C++
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...
?