Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
Example 1:
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Example 2:
Input: root = [1,null,2,null,0,3] Output: 3
Constraints:
[2, 5000].0 <= Node.val <= 105This approach leverages Depth First Search (DFS) to explore the binary tree. The key idea is to maintain the minimum and maximum values observed along the path from the root to the current node. By comparing the current node's value with these min/max values, we can compute potential maximum differences. As we backtrack, we use these values to determine the maximum difference possible for subtree paths.
The function maxAncestorDiffHelper is a recursive helper function that traverses the binary tree using DFS. It keeps track of the current path's minimum and maximum values as parameters. At each node, it updates these values and calculates differences, eventually returning the maximum found.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of nodes in the binary tree, because we visit each node exactly once.
Space Complexity: O(h), where h is the height of the tree, due to the recursive stack usage.
This approach utilizes an iterative Breadth First Search (BFS) paradigm using a queue to traverse the tree. Queue elements consist of a node and associated min/max values for the path leading to this node. As nodes are processed, the difference between node values and min/max path values are calculated to find the maximum difference.
In this solution, a queue is used for BFS traversal, storing node and path min/max values. For each node, we compute current possible differences and keep track of the maximum difference encountered. The solution efficiently processes tree traversal iteratively.
Time Complexity: O(n), as each node is visited once.
Space Complexity: O(n), for the queue storing the nodes in the worst case (when the tree is bushy).
| Approach | Complexity |
|---|---|
| Depth First Search with Min/Max Tracking | Time Complexity: O(n), where n is the number of nodes in the binary tree, because we visit each node exactly once. |
| Breadth First Search (Iterative) | Time Complexity: O(n), as each node is visited once. |
Maximum Difference Between Node and Ancestor | Brute Force | Optimal | Google | Leetcode 1026 • codestorywithMIK • 9,318 views views
Watch 9 more video solutions →Practice Maximum Difference Between Node and Ancestor with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor