Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find difference between node and a descendent in Python
In binary tree problems, we often need to find the maximum difference between a node and its descendants. This involves traversing the tree and tracking the minimum and maximum values in each subtree to calculate the largest absolute difference.
So, if the input is like:
Then the output will be 7, as the largest absolute difference is between nodes 8 and 1.
Algorithm
To solve this, we use a depth-first search (DFS) approach:
- For each node, track the minimum and maximum values in its subtree
- Calculate the maximum difference between the current node and these extreme values
- Return the range [min, max] for the parent node to use
- Keep updating the global maximum difference found so far
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
def dfs(node):
if not node:
return [float("inf"), float("-inf")]
left = dfs(node.left)
right = dfs(node.right)
# Find min and max in current subtree
min_val = min(left[0], right[0], node.val)
max_val = max(left[1], right[1], node.val)
# Update maximum difference
self.ans = max(self.ans, node.val - min_val, max_val - node.val)
return [min_val, max_val]
self.ans = 0
dfs(root)
return self.ans
# Create the tree
ob = Solution()
root = TreeNode(1)
root.left = TreeNode(5)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
root.right.right = TreeNode(8)
root.right.left.left = TreeNode(7)
root.right.left.right = TreeNode(4)
print(ob.solve(root))
7
How It Works
The DFS function returns a pair [min_value, max_value] representing the range of values in the current subtree. For each node:
- We get the range from left and right subtrees
- Calculate the overall min/max including the current node
- Update the answer with the maximum difference between current node and subtree extremes
- Return the range for the parent node
Conclusion
This solution uses DFS to efficiently find the maximum absolute difference between any node and its descendants in O(n) time. The key insight is tracking min/max values in each subtree to calculate differences without multiple traversals.
