|
14 | 14 | * }
|
15 | 15 | */
|
16 | 16 | class Solution {
|
17 |
| - public int maxAncestorDiff(TreeNode root) { |
18 |
| - return dfs(root, root.val, root.val); |
19 |
| - } |
20 |
| - |
21 |
| - private int dfs(TreeNode root, int min, int max) { |
22 |
| - if (root == null) { |
23 |
| - return max - min; |
| 17 | + public int maxAncestorDiff(TreeNode root) { |
| 18 | + int maxDiff = 0; |
| 19 | + Queue<NodeValuePair> queue = new LinkedList<>(); |
| 20 | + queue.add(new NodeValuePair(root, root.val, root.val)); |
| 21 | + while (!queue.isEmpty()) { |
| 22 | + NodeValuePair removed = queue.remove(); |
| 23 | + TreeNode node = removed.node; |
| 24 | + Integer minNodeValue = removed.minNodeValue; |
| 25 | + Integer maxNodeValue = removed.maxNodeValue; |
| 26 | + maxDiff = Math.max(maxDiff, Math.max(Math.abs(node.val - minNodeValue), Math.abs(node.val - maxNodeValue))); |
| 27 | + Integer updatedMinNodeValue = Math.min(node.val, minNodeValue); |
| 28 | + Integer updatedMaxNodeValue = Math.max(node.val, maxNodeValue); |
| 29 | + if (node.left != null) { |
| 30 | + queue.add(new NodeValuePair(node.left, updatedMinNodeValue, updatedMaxNodeValue)); |
| 31 | + } |
| 32 | + if (node.right != null) { |
| 33 | + queue.add(new NodeValuePair(node.right, updatedMinNodeValue, updatedMaxNodeValue)); |
| 34 | + } |
| 35 | + } |
| 36 | + return maxDiff; |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + private static class NodeValuePair { |
| 41 | + private TreeNode node; |
| 42 | + private Integer minNodeValue; |
| 43 | + private Integer maxNodeValue; |
| 44 | + |
| 45 | + public NodeValuePair(TreeNode node, Integer minNodeValue, Integer maxNodeValue) { |
| 46 | + this.node = node; |
| 47 | + this.minNodeValue = minNodeValue; |
| 48 | + this.maxNodeValue = maxNodeValue; |
| 49 | + } |
24 | 50 | }
|
25 |
| - max = Math.max(root.val, max); |
26 |
| - min = Math.min(root.val, min); |
27 |
| - return Math.max(dfs(root.left, min, max), dfs(root.right, min, max)); |
28 |
| - } |
29 | 51 | }
|
0 commit comments