目录
11. 统计左叶子节点的和
/**
* 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 sumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
if(isLeaf(root.left)) return root.left.val + sumOfLeftLeaves(root.left);
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
public int isLeaf(TreeNode node){//返回的条件是这个节点是不是叶子节点,确定是叶子节点,才要去返回。
if(node == null) return false;
return node.left == null && node.right == null;
}
}
12. 相同节点值的最大路径长度![](https://img-blog.csdnimg.cn/ecb516d5895c4d57bcf338512475b88f.png)
/**
* 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 path = 0;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return path;
}
//想写一个从根节点出发的最长同值路径
public int dfs(TreeNode root){
if(root == null) return 0;
int l = dfs(root.left);
int r = dfs(root.right);
int leftPath = root.left != null && root.left.val == root.val ? l + 1 : 0;
int rightPath = root.right != null && root.right.val == root.val ? r + 1 : 0;
path = Math.max(path, leftPath + rightPath);
return Math.max(leftPath, rightPath);//需要返回左边或者右边路径的最大值。进行拼接。
}
}
13. 间隔遍历
/**
* 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 {
Map<TreeNode, Integer> cache = new HashMap<>();
public int rob(TreeNode root) {
if(root == null) return 0;
if(cache.containsKey(root)) return cache.get(root);
int val1 = root.val;
if(root.left != null) val1 += rob(root.left.left) + rob(root.left.right);
if(root.right != null) val1 += rob(root.right.left) + rob(root.right.right);
int val2 = rob(root.left) + rob(root.right);
int res = Math.max(val1, val2);
cache.put(root,res);
return res;
}
}
14. 找出二叉树中第二小的节点 ![](https://img-blog.csdnimg.cn/24adaf183c8949abae36345d3d58d845.png)
public int findSecondMinimumValue(TreeNode root) {
if (root == null) return -1;
if (root.left == null && root.right == null) return -1;
int leftVal = root.left.val;
int rightVal = root.right.val;
if (leftVal == root.val) leftVal = findSecondMinimumValue(root.left);
if (rightVal == root.val) rightVal = findSecondMinimumValue(root.right);
if (leftVal != -1 && rightVal != -1) return Math.min(leftVal, rightVal);
if (leftVal != -1) return leftVal;
return rightVal;
}