Maximum Sum of Non-Adjacent Tree Nodes
Updated
Problem statement
Given the root root of a binary tree with integer node values, choose a set of nodes with maximum possible total value.
No two chosen nodes may be adjacent: if a node is chosen, neither of its children may be chosen. Selecting no nodes is allowed, so the answer is 0 for an empty tree or when every nonempty valid selection has a negative sum.
Return the maximum sum.
Function
maxNonAdjacentSum(root: TreeNode) → longExamples
Example 1
root = [10,1,2]return = 10Choosing only the root gives 10, which is larger than choosing both children for a total of 3.
Example 2
root = [1,2,3,1,null,4,5]return = 11One optimal choice contains the root and the three grandchildren with values 1, 4, and 5, totaling 11.
Example 3
root = [-5,-2,-3]return = 0Every node value is negative, so selecting no nodes gives the maximum sum 0.
Example 4
root = []return = 0An empty tree contains no nodes, so its maximum selectable sum is 0.
Constraints
0 <= number of nodes <= 5 * 10^4-10^9 <= node.val <= 10^9- The input is a valid binary tree.
- The answer fits in a signed
long.
More InMobi Onsite Interview questions
- Russian Doll EnvelopesONSITE INTERVIEW · Seen Jul 2026
- Minimum and Maximum with Optimal ComparisonsONSITE INTERVIEW · Seen Dec 2025
- Minimum Edges to Connect All ComponentsONSITE INTERVIEW · Seen Dec 2025
- Shortest Path Visiting All NodesONSITE INTERVIEW · Seen Sep 2025
- Word SquaresONSITE INTERVIEW · Seen Jan 2022
- Maximum Length Pair ChainONSITE INTERVIEW · Seen Jul 2021
- Top View of a Binary TreeONSITE INTERVIEW · Seen Jul 2021
- Maximum XOR Between Two ArraysONSITE INTERVIEW · Seen May 2021
- Trapping Rain WaterONSITE INTERVIEW · Seen May 2021
- Validate Binary Search TreeONSITE INTERVIEW · Seen May 2021
Similar questions at other companies
- Minimum Root-to-Leaf Cut CostGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Transitive Employee Referral CountsRobinhood · ONSITE INTERVIEWRobinhood interview questions
- Maximum Nonadjacent Sum in a General TreeZip · PHONE SCREEN · ONSITE INTERVIEWZip interview questions
- Distance Sums to Special Nodes in a Weighted TreeNutanix · ONSITE INTERVIEWNutanix interview questions
- File Encryption Tree OptimizationDatabricks · PHONE SCREEN · ONSITE INTERVIEWDatabricks interview questions
- Binary Tree Maximum Path SumGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Binary Tree Maximum Path SumBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Binary Tree Maximum Path SumGlobalization Partners · ONSITE INTERVIEW
- House Robber IIIOkta · PHONE SCREENOkta interview questions
- House Robber IIIVisa · PHONE SCREENVisa interview questions