ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【leetcode】1026. Maximum Difference Between Node and Ancestor

2021-12-31 12:03:57  阅读:153  来源: 互联网

标签:Node node 1026 mmax int res 路径 mmin 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

     这道题的需求是求任意节点和其祖父结点的差值最大值。解题的思路就一句话,这个差值一定是某一路径上最大值和最小值做差得到的,因为在同一路径上的任意两个结点一定互为node和ancestor。 这样就可以用dfs递归维护每一条路径上的最大值最小值,然后在最后一个node上更新result。

class Solution {
public:
    int maxAncestorDiff(TreeNode* root) {
       // 节点和祖父节点的差距 那就是求同一条路径上的最大值和最小值 
       // 任意一条检索路径上 选取任意两个node 一定互为子父结点
       int res=0;
       digui(root,INT_MIN,INT_MAX,res);
       return res;
        
    }
    void digui(TreeNode* node,int mmax,int mmin,int &res){
        // mmax mmin 为由父结点传递下来的当前路径下的最大值和最小值
        if(node==nullptr) return;
        int mmax_=max(mmax,node->val); //更新路径上的最大值
        int mmin_=min(mmin,node->val); //更新路径上的最小值
        if(node->left!=nullptr){
            digui(node->left,mmax_,mmin_,res);
        }
        if(node->right!=nullptr){
            digui(node->right,mmax_,mmin_,res);
        }
        if(node->left==nullptr && node->right==nullptr){
            int diff=abs(mmax_-mmin_);
            res=max(res,diff);
        }
        return;
    }
};

标签:Node,node,1026,mmax,int,res,路径,mmin,Ancestor
来源: https://www.cnblogs.com/aalan/p/15752463.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有