---
# System prepended metadata

title: 1026. Maximum Difference Between Node and Ancestor
tags: [Leetcode, FaceBook, DFS]

---

# 1026. Maximum Difference Between Node and Ancestor
###### tags: `Leetcode` `FaceBook` `DFS`
Link: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
## 思路
找到每条线上的最大最小值 当碰到leaf node的时候结算
## Code
```java=
class Solution {
    int ans = 0;
    public int maxAncestorDiff(TreeNode root) {
        dfs(root, root.val, root.val);
        return ans;
    }
    private void dfs(TreeNode root, int max, int min){
        if(root == null) return;
        ans = Math.max(ans, Math.max(Math.abs(max-root.val), Math.abs(min-root.val)));
        min = Math.min(root.val, min);
        max = Math.max(root.val, max);
        dfs(root.left, max, min);
        dfs(root.right, max, min);
    }
}
```