LeetCode 1026: Maximum Difference Between Node and Ancestor Solution
Master LeetCode problem 1026 (Maximum Difference Between Node and Ancestor), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1026. Maximum Difference Between Node and Ancestor
Problem Explanation
Explanation:
To solve this problem, we can perform a depth-first search (DFS) on the binary tree while keeping track of the minimum and maximum values encountered so far on the path from the root to the current node. At each node, we update the maximum difference by comparing it with the absolute difference between the current node's value and the minimum/maximum values encountered so far.
Algorithm:
- Implement a recursive function
dfsthat takes the current node, the minimum value encountered so far, and the maximum value encountered so far. - If the current node is null, return 0.
- Update the minimum and maximum values encountered so far based on the current node's value.
- Recursively call
dfson the left and right children of the current node, passing the updated minimum and maximum values. - Calculate the maximum difference by taking the maximum of the absolute differences between the current node's value and the updated minimum/maximum values.
- Return the maximum difference.
Time Complexity:
The time complexity of this approach is O(n) where n is the number of nodes in the binary tree.
Space Complexity:
The space complexity is O(h) where h is the height of the binary tree.
: :
Solution Code
class Solution {
public int maxAncestorDiff(TreeNode root) {
return dfs(root, root.val, root.val);
}
private int dfs(TreeNode node, int min, int max) {
if (node == null) return 0;
min = Math.min(min, node.val);
max = Math.max(max, node.val);
int left = dfs(node.left, min, max);
int right = dfs(node.right, min, max);
return Math.max(max - min, Math.max(left, right));
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1026 (Maximum Difference Between Node and Ancestor)?
This page provides optimized solutions for LeetCode problem 1026 (Maximum Difference Between Node and Ancestor) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1026 (Maximum Difference Between Node and Ancestor)?
The time complexity for LeetCode 1026 (Maximum Difference Between Node and Ancestor) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1026 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1026 in Java, C++, or Python.