problem 543. Diameter of Binary Tree 题意: 转换一种角度来看,是不是其实就是根结点1的左右两个子树的深度之和呢.那么我们只要对每一个结点求出其左右子树深度之和,这个值作为一个候选值,然后再对左右子结点分别调用求直径对递归函数,这三个值相互比较,取最大的值更新结果res,因为直径不一定会经过根结点,所以才要对左右子结点再分别算一次.为了减少重复计算,我们用哈希表建立每个结点和其深度之间的映射,这样某个结点的深度之前计算过了,就不用再次计算了. solution…
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode.com/problems/diameter-of-binary-tree/#/description 题目描述 Given a binary tree, you need to compute the length of the diameter of the tree. The diameter…
题目如下: 解题思路:最长的周长一定是树中某一个节点(不一定是根节点)的左右子树中的两个叶子节点之间的距离,所以最简单的办法就是把树中所有节点的左右子树中最大的两个叶子节点之间的距离求出来,最终得到最大值. 代码如下: # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class So…
problem 993. Cousins in Binary Tree 参考 1. Leetcode_easy_993. Cousins in Binary Tree; 完…
[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 递归和非递归,此提比较简单.广度优先遍历即可.关键之处就在于如何保持访问深度. 下面是4种代码: im…
124. Binary Tree Maximum Path Sum https://www.cnblogs.com/grandyang/p/4280120.html 如果你要计算加上当前节点的最大path和,这个节点的左右子树必定是纯左右树(即没有拐点), 用另一个参数保留整个二叉树的最大path和,然后计算每一个以当前节点为拐点的路径和并且不断更新整个二叉树的最大值 函数的返回值是纯左右子树的最大path,没有拐点 这个题目给root定位为非空,所以直接这样写可以.如果root为空,这样写就会…
[CF438E]The Child and Binary Tree(多项式运算,生成函数) 题面 有一个大小为\(n\)的集合\(S\) 问所有点权都在集合中,并且点权之和分别为\([0,m]\)的二叉树的个数. \(n,m<=10^5\) 题解 设\(f(i)\)表示点权和为\(i\)的二叉树个数,\(c(i)\)是集合中数的生成函数,那么我们可以得到 \[f(n)=\sum_{i=1}^{n}c(i)\sum_{j=0}^{n-i}f(j)f(n-i-j)\] 显然有\(f(0)=1\) 构…
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example:Given a binary t…
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 递归的解题思路: 递归当前结点,分一下四种情况考虑:①结点为空时返回0:②结点没有右子树时,返回左子树最小值+1:③结点没有左子树时,返回右子树最小值+1:④当结点双子齐全时,返回…
https://leetcode.com/problems/diameter-of-binary-tree/#/description Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This…