提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
像求和、求高度这种基本的二叉树函数很容易写,有时候只要在它们的后序位置添加一点代码,就能得到我们想要的答案。
一、力扣549. 二叉树中最长的连续序列
/**
* 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 res = 0;
public int longestConsecutive(TreeNode root) {
fun(root);
return res;
}
public int[] fun(TreeNode root){
if(root == null){
return new int[]{0,0};
}
int[] left = fun(root.left);
int[] right = fun(root.right);
int leftInc = left[0], leftDes = left[1];
int rightInc = right[0], rightDes = right[1];
int curInc = 1, curDes = 1;
if(root.left != null){
if(root.left.val -1 == root.val){
curInc += leftInc;
}
if(root.left.val + 1 == root.val){
curDes += leftDes;
}
}
if(root.right != null){
if(root.right.val - 1 == root.val){
curInc = Math.max(curInc,rightInc+1);
}
if(root.right.val + 1 == root.val){
curDes = Math.max(curDes, rightDes+1);
}
}
res = Math.max(res, curInc + curDes -1);
return new int[]{curInc,curDes};
}
}
二、力扣1325. 删除给定值的叶子节点
/**
* 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 TreeNode removeLeafNodes(TreeNode root, int target) {
if(root == null){
return null;
}
if(root.left == null && root.right == null){
if(root.val == target){
return null;
}
}
TreeNode left = removeLeafNodes(root.left,target);
TreeNode right = removeLeafNodes(root.right,target);
if(left == null && right == null){
if(root.val == target){
return null;
}
}
root.left = left;
root.right = right;
return root;
}
}
文章介绍了在二叉树中寻找最长连续序列的力扣549题解,以及如何删除给定值的叶子节点的力扣1325题。通过递归方法处理节点关系,实现高效求解。
741

被折叠的 条评论
为什么被折叠?



