LeetCode-1026. 节点与其祖先之间的最大差值-深度优先搜索

/** 1026. 节点与其祖先之间的最大差值

* @author 作者 Your-Name:

* @version 创建时间:2020年3月5日 上午9:44:01

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

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

示例:

输入:[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 得出。


*/

public class 节点与其祖先之间的最大差值 {
	public class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	  }
	int ans=0;
	public int maxAncestorDiff(TreeNode root) {
		dfs(root,root.val,root.val);
		return ans;
    } 
	public void dfs(TreeNode root,int max,int min)
	{
		if(root==null)
			return;
		max = Math.max(root.val, max);
		min = Math.min(root.val, min);
		if(root.left==null&&root.right==null)
		{
			ans = Math.abs(max-min);
		}
		dfs(root.left,root.left.val,root.left.val);
		dfs(root.right,root.right.val,root.right.val);
		
	}
}
发布了72 篇原创文章 · 获赞 7 · 访问量 4103

猜你喜欢

转载自blog.csdn.net/l769440473/article/details/104669832