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 }