Day17题目
LeetCode110.平衡二叉树
核心思想:每个节点都判断是不是平衡二叉树,就是判断每个节点的左右子树的高度差是否大于1
class Solution {
public boolean isBalanced(TreeNode root) {
// 求每个节点的左右节点高度差,超过1则直接返回false
return getHeight(root) != -1 ;
}
public int getHeight(TreeNode root){
if(root == null) return 0;
int leftDepth = getHeight(root.left);
int rightDepth = getHeight(root.right);
// 如果有一个子树的高度差大于1,那么整个都返回-1
if(leftDepth == -1 || rightDepth == -1) return -1;
// 如果当前树高度差大于1,返回-1
if(Math.abs(leftDepth - rightDepth) > 1) return -1;
// 返回当前树的高度
return Math.max(leftDepth,rightDepth)+1;
}
}
LeetCode二叉树的所有路径
核心思想:哪种遍历都能做,但是使用中序+回溯更快
class Solution {
// 记录当前路径的点
List<Integer> path = new ArrayList<>();
// 返回值
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
path = new ArrayList<>();
res = new ArrayList<>();
help(root);
return res;
}
public void help(TreeNode root){
// 路径都是从根节点开始的
path.add(root.val);
// 如果一个节点是叶子节点了,就加入到结果集。
if(root.left == null && root.right == null ){
StringBuilder sb = new StringBuilder();
// 构造结果
for(int i = 0; i < path.size()-1 ; i ++){
sb.append(path.get(i));
sb.append("->");
}
// 最后一个不在末尾加->所以单独处理
sb.append(path.get(path.size()-1));
res.add(sb.toString());
}
// 然后遍历左和右子树
if(root.left != null){
help(root.left);
// 这里进行回溯,因为遍历完左子树后,path里面多了左叶子的节点,想要继续遍历右子树,就要删去左子树遍历的这个节点。
path.remove(path.size()-1);
}
if(root.right != null){
help(root.right);
// 回溯
path.remove(path.size()-1);
}
}
}
LeetCode 404.左叶节点之和
核心思想:使用root.left!=null && root.left.left == null && root.left.right == null 来判断符合条件的节点。
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
help(root);
return sum;
}
public void help(TreeNode root){
if(root == null) return;
if(root.right != null){
// 右子树可能也有符合条件的左叶子节点
help(root.right);
}
if(root.left != null){
// 如果符合条件就加结果
if(root.left.left == null && root.left.right == null){
sum += root.left.val;
}else{
// 如果不符合条件那么左子树可能有符合条件的,继续遍历
// 加上else的内存占用比不加还多。
help(root.left);
}
}
}
}
428



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



