110.平衡二叉树
import javax.swing.tree.TreeNode;
public class BalancedBinaryTree {
/**
* 递归法-后序-高度
* 左右中-左右子树判断之后再反对父节点
*/
public boolean isBalanced(TreeNode root){
return getHeight(root) != -1;
}
public 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;
// 左右子树高度差大于1,return -1表示已经不是平衡树了
if(Math.abs(leftHeight - rightHeight) > 1){
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
257. 二叉树的所有路径
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePaths {
/**
* 递归法-前序-回溯
*/
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));//获取path长度,结果!!
res.add(sb.toString());//转为string
return;//完整path
}
//左
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.左叶子之和
public class SumofLeftLeaves {
//递归-后序
public int sumOfLeftLeaves(TreeNode root){
if(root == null) return 0;
if(root.left == null && root.right == 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;
}
}