详细题目见Leetcode第1026题
思路:
祖先的定义是什么?祖先指根A到结点K的唯一路径上的任意结点
找出某个节点与祖先的最大值,可以转化成到叶节点的每个路径中的最大差值
所以可以通过深度优先遍历找到每个路径,然后找到每个路径上的最大最小点,计算最大差值
*遍历是树各种操作的基础,再遍历的过程中能对结点进行许多操作。而遍历通过递归实现,会比较简单!
DFS(深度优先遍历):
class Solution {
public:
void dfs(TreeNode* root,int maxnum,int minnum,int &maxdiff){
if(root->val > maxnum){
maxnum = root->val;
maxdiff = max(maxnum - minnum,maxdiff);
}
else if(root->val < minnum){
minnum = root->val;
maxdiff = max(maxnum - minnum,maxdiff);
}
//先找左树
if(root->left != nullptr){
dfs(root->left,maxnum,minnum,maxdiff);
}
//再找右树
if(root->right != nullptr){
dfs(root->right,maxnum,minnum,maxdiff);
}
}
int maxAncestorDiff(TreeNode* root) {
int maxnum = root->val,minnum = root->val;
int maxdiff = maxnum - minnum;
dfs(root,maxnum,minnum,maxdiff);
return maxdiff;
}
};
class Solution {
public:
int dfs(TreeNode *root, int mi, int ma) {
if (root == nullptr) {
return 0;
}
int diff = max(abs(root->val - mi), abs(root->val - ma));
mi = min(mi, root->val);
ma = max(ma, root->val);
diff = max(diff, dfs(root->left, mi, ma));
diff = max(diff, dfs(root->right, mi, ma));
return diff;
}
int maxAncestorDiff(TreeNode* root) {
return dfs(root, root->val, root->val);
}
};
*标准答案,和我的不同点在于,我的写法把最大差值作为变量,而这个写法把最大差值作为返回值返回,所以更简洁