久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

1026. Maximum Difference Between Node and Ancestor (M)

 小樣樣樣樣樣樣 2022-10-07 發(fā)布于北京

Maximum Difference Between Node and Ancestor (M)

題目

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 <= 10^5

題意

找到一組結(jié)點(diǎn),,其中一個(gè)是另一個(gè)祖先結(jié)點(diǎn),使得這兩個(gè)結(jié)點(diǎn)的差值最大,。

思路

遞歸處理,,兩種方法:

  1. 每次找到左子樹(shù)和右子樹(shù)中的最值,以此更新結(jié)果,。
  2. 每次遞歸更新當(dāng)前路徑上的最大值和最小值,,到達(dá)葉結(jié)點(diǎn)時(shí)計(jì)算差值并返回。

代碼實(shí)現(xiàn)

Java

遞歸1

class Solution {
    private int diff;

    public int maxAncestorDiff(TreeNode root) {
        diff = 0;
        dfs(root);
        return diff;
    }

    private int[] dfs(TreeNode root) {
        if (root == null) {
            return null;
        }

        int[] l = dfs(root.left), r = dfs(root.right);

        if (l == null && r == null) {
            return new int[] { root.val, root.val };
        }

        int cMin = 0, cMax = 0;
        if (l != null && r != null) {
            cMin = Math.min(l[0], r[0]);
            cMax = Math.max(l[1], r[1]);
        } else if (l != null) {
            cMin = l[0];
            cMax = l[1];
        } else {
            cMin = r[0];
            cMax = r[1];
        }
        diff = Math.max(diff, Math.max(Math.abs(root.val - cMin), Math.abs(root.val - cMax)));
        return new int[] { Math.min(root.val, cMin), Math.max(root.val, cMax) };
    }
}

遞歸2

class Solution {
    public int maxAncestorDiff(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return dfs(root, root.val, root.val);
    }

    private int dfs(TreeNode root, int max, int min) {
        if (root == null) {
            return max - min;
        }

        max = Math.max(root.val, max);
        min = Math.min(root.val, min);
        return Math.max(dfs(root.left, max, min), dfs(root.right, max, min));
    }
}

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,,所有內(nèi)容均由用戶(hù)發(fā)布,,不代表本站觀(guān)點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式,、誘導(dǎo)購(gòu)買(mǎi)等信息,,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請(qǐng)點(diǎn)擊一鍵舉報(bào),。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多