[LeetCode] 1026. Maximum Difference Between Node and Ancestor
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:
- The number of nodes in the tree is in the range
[2, 5000]
. 0 <= Node.val <= 105
节点与其祖先之间的最大差值。
给定二叉树的根节点 root,找出存在于不同节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。
(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-difference-between-node-and-ancestor
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 DFS 前序遍历。题目让你找的是二叉树里面两个不同节点之间的最大差值,这两个节点要在同一条分支上。那么我们可以用 DFS 前序遍历,在遍历的过程中,记录一下当前路径上节点的最大值和最小值。当我们到达叶子节点的时候,则可以计算一下这个差值是多少。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int maxAncestorDiff(TreeNode root) { 18 if (root == null) { 19 return 0; 20 } 21 return helper(root, root.val, root.val); 22 } 23 24 private int helper(TreeNode root, int max, int min) { 25 // base case 26 if (root == null) { 27 return max - min; 28 } 29 max = Math.max(max, root.val); 30 min = Math.min(min, root.val); 31 int left = helper(root.left, max, min); 32 int right = helper(root.right, max, min); 33 return Math.max(left, right); 34 } 35 }
二刷的时候完全看不懂第一次刷的代码了。这道题还是用前序遍历做,只不过我把最后的结果存在一个全局变量 res 里。每次遇到一个不为空的节点,就更新最大值和最小值。当我们走到最后的叶子节点的时候,我们就更新 res。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 int res = 0; 18 19 public int maxAncestorDiff(TreeNode root) { 20 if (root == null) { 21 return 0; 22 } 23 helper(root, root.val, root.val); 24 return res; 25 } 26 27 private void helper(TreeNode root, int max, int min) { 28 if (root == null) { 29 return; 30 } 31 max = Math.max(max, root.val); 32 min = Math.min(min, root.val); 33 if (root.left == null && root.right == null) { 34 res = Math.max(res, max - min); 35 } 36 helper(root.left, max, min); 37 helper(root.right, max, min); 38 } 39 }