Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 1026. Maximum Difference Between Node and Ancestor #239

Open
Woodyiiiiiii opened this issue Apr 18, 2023 · 0 comments
Open

Leetcode 1026. Maximum Difference Between Node and Ancestor #239

Woodyiiiiiii opened this issue Apr 18, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Apr 18, 2023

1026. Maximum Difference Between Node and Ancestor

这里有两种解法。

一、自底向上——归

这种写法也是大多数dfs、记忆化搜索的写法。将每个结点看成祖先,求它左右子结点的最小值和最大值,所以返回值是多个,要返回数组。后序遍历的翻版。

class Solution {

    int ans = 0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root);
        return ans;    
    }

    private int[] dfs(TreeNode root) {
        if (root == null) {
            return new int[]{-1,-1};
        }
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        int max = root.val, min = root.val;
        if (left[0] != -1) {
            ans = Math.max(ans, Math.abs(left[0] - root.val));
            ans = Math.max(ans, Math.abs(left[1] - root.val));
            min = Math.min(min, left[0]);
            max = Math.max(max, left[1]);
        }
        if (right[0] != -1) {
            ans = Math.max(ans, Math.abs(right[0] - root.val));
            ans = Math.max(ans, Math.abs(right[1] - root.val));
            min = Math.min(min, right[0]);
            max = Math.max(max, right[1]);
        }
        return new int[]{min, max};
    }
}

二、自顶向下——递

这种写法是跟上述反过来。将每个结点看成子结点,求所有祖先结点的最小值和最大值。先序遍历的翻版。

class Solution {

    int ans = 0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root, root.val, root.val);
        return ans;
    }

    private void dfs(TreeNode root, int mn, int mx) {
        if (root == null) return;
        mn = Math.min(root.val, mn);
        mx = Math.max(root.val, mx);
        ans = Math.max(ans, Math.max(Math.abs(root.val - mn), Math.abs(root.val - mx)));
        dfs(root.left, mn, mx);
        dfs(root.right, mn, mx);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant