LC.P1026[节点与其祖先之间的最大差值] 方法一:DFS通过DFS,记录以该节点为根节点的路径上的最大值与最小值,最后更新答案。 1234567891011121314151617181920212223242526272829303132/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */class Solution { int ans; public int maxAncestorDiff(TreeNode root) { dfs(root, root.val, root.val); return ans; } private void dfs(TreeNode node, int max, int min) { if (node == null) return; max = Math.max(max, node.val); min = Math.min(min, node.val); dfs(node.left, max, min); dfs(node.right, max, min); ans = Math.max(ans, max - min); }}