AlgoMaster Logo

Maximum Difference Between Node and Ancestor

tree=[8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
1class Solution {
2    public int maxAncestorDiff(TreeNode root) {
3        // Start DFS from the root node with its own value as both min and max.
4        return dfs(root, root.val, root.val);
5    }
6
7    private int dfs(TreeNode node, int minVal, int maxVal) {
8        if (node == null) {
9            // If node is null, return the difference between max and min values found so far.
10            return maxVal - minVal;
11        }
12
13        // Update min and max values on this path as we go deeper into the tree.
14        minVal = Math.min(minVal, node.val);
15        maxVal = Math.max(maxVal, node.val);
16
17        // Travel down both children and get their max differences.
18        int leftMaxDiff = dfs(node.left, minVal, maxVal);
19        int rightMaxDiff = dfs(node.right, minVal, maxVal);
20
21        // Return the maximum difference obtained from either subtree.
22        return Math.max(leftMaxDiff, rightMaxDiff);
23    }
24}
0 / 85
831016144713