前言
###我做这类文章一个重要的目的还是给正在学习的大家提供方向(例如想要掌握基础用法,该刷哪些题?建议灵神的题单和代码随想录)和记录自己的学习过程,我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.最深叶节点的最近公共祖先
题目链接: 1123. 最深叶节点的最近公共祖先 - 力扣(LeetCode)
题面:
代码:
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 maxdep = 0;
TreeNode ans = null;
int sum = 0;
public TreeNode lcaDeepestLeaves(TreeNode root) {
recursion2(root,0);
// System.out.println(maxdep+" "+sum);
recursion(root,0);
return ans;
}
public int recursion(TreeNode node,int dep){
if(node==null){
return 0;
}
if(node.left==null&&node.right==null){
if(dep==maxdep){
if(sum==1){
ans = node;
return 99999;
}
return 1;
}
return 0;
}
int l = recursion(node.left,dep+1);
int r = recursion(node.right,dep+1);
if((l+r)==sum){
ans = node;
return 99999;
}
return (l+r);
}
public void recursion2(TreeNode node,int dep){
if(node==null){
return;
}
if(node.left==null&&node.right==null){
if(dep>maxdep){
maxdep = dep;
sum = 1;
}else if(maxdep==dep){
sum++;
}
}
recursion2(node.left,dep+1);
recursion2(node.right,dep+1);
}
}
2.从二叉树一个节点到另一个节点的每一步的方向
题目链接: 2096. 从二叉树一个节点到另一个节点每一步的方向 - 力扣(LeetCode)
题面:
注意递归遍历树的时候别在参数拼接树,当树太大会OOM,用StringBuilder
代码:
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 {
TreeNode linP = null;
int startValue;
int destValue;
String start = "";
String dest = "";
public String getDirections(TreeNode root, int startValue, int destValue) {
this.startValue = startValue;
this.destValue = destValue;
int sign = recursion2(root);
if(sign==2){
linP = root;
}
StringBuilder sb = new StringBuilder();
recursion(linP,sb);
// System.out.println(start+" "+dest);
int size = start.length();
String ans = "";
while(size>0){
size--;
ans+="U";
}
if(dest.equals("")){
return ans;
}
if(start.equals("")){
return dest;
}
return ans+dest;
}
public void recursion(TreeNode node,StringBuilder sb){
if(!dest.equals("")&&!start.equals(""))return;
if(node==null)return;
if(node.val==startValue){
start = sb.toString();
}else if(node.val==destValue){
dest = sb.toString();
}
recursion(node.left,sb.append("L"));
sb.deleteCharAt(sb.length()-1);
recursion(node.right,sb.append("R"));
sb.deleteCharAt(sb.length()-1);
}
public int recursion2(TreeNode node){
if(linP!=null)return 99999;
if(node==null)return 0;
int l = recursion2(node.left);
int r = recursion2(node.right);
if(node.val==startValue||node.val==destValue){
int sum = l+r+1;
if(sum==2){
linP = node;
return 9999;
}
return sum;
}
if((l+r)==2){
linP = node;
return 99999;
}
return l+r;
}
}
后言
上面是数据结构相关的习题,下一篇文章会将其他相关的习题。