110. 平衡二叉树
思路:后序遍历递归求左右子树的高度,如果左右子树的高度差大于1就返回-1,即为非平衡二叉树。
class Solution {
public boolean isBalanced(TreeNode root) {
return getHigh(root) != -1;
}
private int getHigh(TreeNode node){
if (node == null){
return 0;
}
int left = getHigh(node.left);
if(left == -1){
return -1;
}
int right = getHigh(node.right);
if(right == -1){
return -1;
}
if(Math.abs(left - right) > 1){
return -1;
}
return Math.max(left, right)+1;
}
}
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();// 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);// 回溯
}
}
}
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 sum = midValue + leftValue + rightValue; // 中
return sum;
}
}