对于所有的递归问题和DP问题,一定要先想清楚问题是由哪些子问题构成,搞清楚了这个,就完成了80%的工作。
二叉树的遍历问题基本都是以求二叉树的高度的代码为模版出的题:
//问题的子问题是:某个节点的高度 == 左子树与右子树当中高度最大的那个 + 1
public int height(TreeNode root) {
if (root == null) return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}
[LeetCode] Longest Univalue Path 最长相同值路径
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output:
2 Example 2:
Input:
1 / \ 4 5 / \ \ 4 4 5
Output: 2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
这题需要注意的是线 路径是可以从 node.left-> node ->node.right,弯的!
这题与求书的高度那题多了两个东西:
1. 判定什么时候增加resl,resr,当发现 node值跟孩子的值不行等时立马将resl/resr变为0,即切断了路线,使其不向上传播。
2.增加了lup来存储最大的路径长度,有点类似于动态规划。
//问题的子问题是:先不考虑路径穿过中间节点的情况。对于某个节点node1而言,它的maxlen 等于 左子树或右子树当中的最大的len(如果与node1.val相等,就+1),那么lup = max(lup, resl ,resr);。然后,考虑路径穿过中间节点node1的情况。lup就变为lup = max(lup, resl + resr);
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int lup = 0;
if (root) dfs(root, lup);
return lup;
}
private:
int dfs(TreeNode* node, int& lup) {
int l = node->left ? dfs(node->left, lup) : 0;
int r = node->right ? dfs(node->right, lup) : 0;
int resl = node->left && node->left->val == node->val ? l + 1 : 0;
int resr = node->right && node->right->val == node->val ? r + 1 : 0;
lup = max(lup, resl + resr);
return max(resl, resr);//类似于返回树的高度
}
};
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
#写二叉树递归代码,先搭建好框架。即先写参数列表,再写代码开始的 终结条件,再写左子树遍历,再写右子树遍历。
//问题的子问题是,对于某个节点node1而言,node1的maxPath等于MAX{左子树的maxVal ,右子树的maxVal, 左子树的maxVal+右子树的maxVal + node1.val}。子模块间传递的值是不考虑穿过node1的情况。另外,如果左子树的maxVal或右子树的maxVal 为负数,则舍弃该路径,反之,将该路径加到自己的路径中。
public class Solution {
int maxValue;
public int maxPathSum(TreeNode root) {
maxValue = Integer.MIN_VALUE;
maxPathDown(root);
return maxValue;
}
private int maxPathDown(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
maxValue = Math.max(maxValue, left + right + node.val);
return Math.max(left, right) + node.val;
}
}