110 平衡二叉树
https://leetcode.cn/problems/balanced-binary-tree/
class Solution {
public boolean isBalanced(TreeNode root) {
return heightOrBalanced(root) >= 0;
}
private int heightOrBalanced(TreeNode root) {
if (root == null) return 0;
int leftHeight = heightOrBalanced(root.left);
if (leftHeight < 0) return -1;
int rightHeight = heightOrBalanced(root.right);
if (rightHeight < 0) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
}
257 二叉树的所有路径
https://leetcode.cn/problems/binary-tree-paths/description/
所有路径这么明显dfs的题我第一反应居然是recursion 后序遍历做,两种都写了。值得注意的是这题的base case要包括left node。
class Solution { // recursion 后序遍历
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) return result;
if (root.left == null && root.right == null) {
result.add(Integer.toString(root.val));
return result;
}
List<String> leftPath = binaryTreePaths(root.left);
List<String> rightPath = binaryTreePaths(root.right);
for (String str : leftPath) {
result.add(Integer.toString(root.val) + "->" + str);
}
for (String str : rightPath) {
result.add(Integer.toString(root.val) + "->" + str);
}
return result;
}
}
class Solution { // dfs 回溯 前序遍历
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
StringBuilder sb = new StringBuilder();
dfs(root, result, sb);
return result;
}
private void dfs(TreeNode root, List<String> result, StringBuilder sb) {
if (root == null) {
return;
}
int len = sb.length();
if (root.left == null && root.right == null) {
sb.append(String.valueOf(root.val));
result.add(new String(sb));
sb.setLength(len);
return;
}
sb.append(String.valueOf(root.val));
sb.append("->");
dfs(root.left, result, sb);
dfs(root.right, result, sb);
sb.setLength(len);
}
}
404 左叶子之和
https://leetcode.cn/problems/sum-of-left-leaves/description/
后序遍历的递归。每层里的逻辑:每层里计算左叶子=两边子树给的+算上自己新产生的。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int result = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
result += root.left.val;
}
return result + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}