17-1.110平衡二叉树
题目
思路
递归法
代码
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
private int getHeight(TreeNode root) {
if (root == null) return 0;
int leftHeight = getHeight(root.left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(root.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight,rightHeight) + 1;
}
}
17-2.257二叉树的所有路径
题目
思路
递归法
代码
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
List<Integer> paths = new ArrayList<>();
traversal(root, paths, res);
return res;
}
private void traversal(TreeNode root, List<Integer> paths, List<String> res) {
paths.add(root.val);
if (root.left == null && root.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)); //记录最后一个节点
res.add(sb.toString());
return;
}
if (root.left != null) {
traversal(root.left, paths, res);
paths.remove(paths.size() - 1); //回溯
}
if (root.right != null) {
traversal(root.right, paths, res);
paths.remove(paths.size() - 1); //回溯
}
}
}
17-3.404左叶子之和
题目
思路
递归法
代码
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int leftValue = sumOfLeftLeaves(root.left); //左
int rightvalue = sumOfLeftLeaves(root.right); //右
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int res = leftValue + rightvalue + midValue; //中
return res;
}
}