本文主要是介绍小黑喜迎国庆胡吃海塞,等待降温的leetcode之旅:1026. 节点与其祖先之间的最大差值(祝中老黑蓝港今日约妹马到成功),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
小黑暴力求解
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:if not root:return -1def pre_node(root):q = [root]display = []while q:node = q.pop()display.append(node)if node.right:q.append(node.right)if node.left:q.append(node.left)return displaydisplay = pre_node(root)max_ = -1for node in display:dis = pre_node(node)for n in dis:if abs(node.val-n.val) > max_:max_ = abs(node.val-n.val)return max_
先序遍历法(python)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:self.dfs = 0def dfs(node,min_,max_):if not node:returnmin_ = min(min_,node.val)max_ = max(max_,node.val)if not (node.left or node.right):self.dfs = max(self.dfs,max_- min_)dfs(node.left,min_,max_)dfs(node.right,min_,max_)dfs(root,root.val,root.val)return self.dfs
先序遍历法(java)
/*** 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 {int ans = 0;public int maxAncestorDiff(TreeNode root) {dfs(root,root.val,root.val);return this.ans;}public void dfs(TreeNode node,int min,int max){if(node == null){return ;}min = (min > node.val) ? node.val:min;max = (max < node.val) ? node.val:max;if(node.left == null && node.right == null){this.ans = (this.ans < max - min) ? max - min:this.ans;}else{dfs(node.left,min,max);dfs(node.right,min,max);}}
}
小黑生活
此时此刻
阴雨天跑个步
昨日一个人又去蓝港啦
又去朝阳公园溜溜
回家的路上淋雨+满血红灯
下午打算去国贸待会儿~祝中老黑今日约会成功!!!
这篇关于小黑喜迎国庆胡吃海塞,等待降温的leetcode之旅:1026. 节点与其祖先之间的最大差值(祝中老黑蓝港今日约妹马到成功)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!