day17 打卡110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和
day17 打卡110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和
110.平衡二叉树
1.递归法
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode node) {
if (node == null) return 0;
int leftHeight = getHeight(node.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = getHeight(node.right);
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight-rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight)+1;
}
}
257. 二叉树的所有路径
1.递归法,回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) return result;
// 作为结果中的路径
List<Integer> paths = new ArrayList<>();
traversal(root, paths, result);
return result;
}
public void traversal(TreeNode node, List<Integer> paths, List<String> result) {
paths.add(node.val);
if (node.left == null && node.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i<paths.size()-1 ; i++) {
sb.append(paths.get(i)).append("->");
}
sb.append(paths.get(paths.size()-1));
result.add(sb.toString());
return;
}
// 递归和回溯是同时进行
if (node.left != null) {
traversal(node.left, paths, result);
paths.remove(paths.size()-1);
}
if (node.right != null) {
traversal(node.right, paths, result);
paths.remove(paths.size()-1);
}
}
}
404.左叶子之和
1.递归法
class Solution {
public int sumOfLeftLeaves(TreeNode node) {
if (node == null) return 0;
if (node.left == null && node.right == null) return 0;
// 左
int leftNum = sumOfLeftLeaves(node.left);
// 右
int rightNum = sumOfLeftLeaves(node.right);
int midNum = 0;
if (node.left != null && node.left.left == null && node.left.right == null) {
midNum = node.left.val;
}
// 中
return leftNum + rightNum + midNum;
}
}

浙公网安备 33010602011771号