节点与其祖先之间的最大差值

问题:

给定二叉树的根节点 root,找出存在于 不同 节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。

(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)

示例 1:

输入:root = [8,3,10,1,6,null,14,null,null,4,7,13]
输出:7
解释: 
我们有大量的节点与其祖先的差值,其中一些如下:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
示例 2:


输入:root = [1,null,2,null,0,3]
输出:3

提示:

树中的节点数在 2 到 5000 之间。
0 <= Node.val <= 105

思路:

根据二叉树前序遍历的思想对二叉树进行嵌套递归,不仅对每个树节点进行前序遍历还对每个节点的孩子节点进行前序遍历。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxAncestorDiff(TreeNode root) {
        int ans = 0;
        ans = preMethod(ans,root);
        return ans;

    }
    public int preMethod(int ans, TreeNode root){
        if(root == null){
            return ans;
        }
        int lans = preChlidMethod(ans,root,root.left);
        int rans = preChlidMethod(ans,root,root.right);
        int tem = Math.max(lans,rans);
        ans = Math.max(ans,tem);
        int llans = preMethod(ans,root.left);
        int rrans = preMethod(ans,root.right);
        int ttem = Math.max(llans,rrans);
        ans = Math.max(ttem,ans);
        return ans;
    }
    public int preChlidMethod(int ans, TreeNode root, TreeNode child){
        if(root !=null && child != null){
            ans = Math.max(Math.abs(root.val - child.val),ans);
            int ansl = preChlidMethod(ans,root,child.left);
            int ansr = preChlidMethod(ans,root,child.right);
            int tem = Math.max(ansl,ansr);
            ans = Math.max(tem,ans);
            return ans; 
        }
        else {
            return ans;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值